When working with terraform there will come a time when you need to create multiple variotions of the same resources. Using a for_each in terraform can help reduce code duplication and make deploying resources a lot easier. In this example I’m going to walk through how to create an Azurerm Subnet using the for_each argument.
Step 1: Define a Map Variable
Define a map variable that represents the desired subnets. The keys of the map can be used as unique identifiers for each subnet.
variable "subnets" {
type = map(object({
name = string
address_prefix = string
security_group = string
}))
}
Now that we defined the variable map, we need to create the azurerm subnet resource.
Step 2: Create Subnets
Use the azurerm_subnet resource block and the for_each loop to create the subnets based on the map variable.
resource "azurerm_subnet" "main" {
for_each = var.subnets
name = each.value.name
resource_group_name = azurerm_resource_group.main.name
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = [each.value.address_prefix]
network_security_group_id = azurerm_network_security_group.example[each.value.security_group].id
}
Now we have our for_each with loops through our variable by using var.subnets. We are grabbing the name of each subnet by using each.value.name. We then take the address prefixes an the network security group. If we wanted we could of also made the virtual network a part of the map as well.
Step 3: Define the Subnets
Inside of our variables we need to now define what subnets that we want created. Now this is where we are able to create multiple subnets and not have to create the same resource block over again.
variable "subnets" {
type = map(object({
name = string
address_prefix = string
security_group = string
}))
default = {
subnet1 = {
name = "subnet1"
address_prefix = "10.0.1.0/24"
security_group = "security_group1"
},
subnet2 = {
name = "subnet2"
address_prefix = "10.0.2.0/24"
security_group = "security_group2"
}
}
}
Each subnet has a unique key, and the corresponding values contain the subnet properties.
Conclusion
This helps prevent code duplication in areas that are not needed. This terraform for_each method can be used for many other types of resources that you may deploy in azure or any other cloud provider.