I have my azure cloud setup manually. It almost has 5 subnets. Now in order to make it IAAS, I am writing a Terraform code for it. I know, I can import resource by using the command "terraform import azurerm_subnet.mysybnet ". This only imports one subnet. How can I import multiple subnets? For example, if I have subnets with names "vm-subnet", "aks-subnet", "acr-subnet", "nsg-subnet" and "firewall-subnet". How can I import all these subnets in one shot?
My current code is
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "=3.0.0"
}
}
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "myrg" {
name = "myRG"
location = "WEST US 2"
}
resource "azurerm_virtual_network" "myvnet" {
name = "myvnet"
resource_group_name = azurerm_resource_group.myrg.name
location = azurerm_resource_group.myrg.location
address_space = ["10.0.0.0/16"]
}
#Create subnets within the resource group
resource "azurerm_subnet" "mysubnet" {
name = "acr-subnet"
address_prefixes = ["10.0.0.0/24"]
resource_group_name = azurerm_resource_group.myrg.name
virtual_network_name = azurerm_virtual_network.myvnet.name
}
2
Answers
A common requirement is to import multiple resources into a Terraform state at once. You have to import each resource individually.
The problem with your scenario is that
terraform import
only works for single resources. If you want to import multiple resources of the same kind (such as subnets), you have to run the import command multiple times, giving a different identifier for each resource in your Terraform configuration.My preexisiting resources in portal
Define the Terraform Configuration for Each Subnet: Before importing, you must have a Terraform resource block for each subnet you wish to import.
Use a Script to Automate the Import Process: Write a shell script (or a script in another language) that runs
terraform import
for each subnet.My Terraform configuration:
Shell script:
Before executing the command, make sure both files are in the same directory and follow the steps below.
Step 1:
Run the command
terraform init
Step 2:
Now execute the commands
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
&
.Import-Subnets.ps1
This commands will starts executing the commands inside the shell scripts.
Output:
This step is executed repeatedly until the given list is fully processed.
Step3:
Now run the command
terraform state list
Depending on the version of terraform you are using, you can now use
import
blocks withfor_each
, which works on the terraform versions >1.7.x. For example: