I am trying to create Azure virtual network ( azurerm_virtual_network ) and Subnets based on the input json local block.
locals {
networks = {
hub-vnet = {
address_space = ["10.0.0.0/9"]
subnets = {
app = {
address_prefix = ["10.1.0.0./16"]
enable_netgateway = false
},
db = {
address_prefix = ["10.2.0.0./16"]
enable_netgateway = true
}
}
}
}
}
locals {
vnet_details = flatten([
for k, v in local.networks : {
// Nested for loop to read the map in values
for snet_k, snet_val in v.subnets :
snet_k => merge(
{
vnetName = k
vnet_addresspace = v.address_space
subnetName = snet_k
}, snet_val
)
// Filtering
if(snet_val.enable_netgateway == true)
}
])
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_virtual_network" "example" {
for_each = { for item in local.vnet_details : item.subnetName => item }
name = each.value.vnetName
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
address_space = each.value.vnet_addresspace
}
resource "azurerm_subnet" "example" {
for_each = { for item in local.vnet_details : item.subnetName => item }
name = each.value.subnetName
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example[each.key].name
address_prefixes = each.value.address_prefix
}
Expectation is create app subnet but I am getting below error. Could someone help me what is missing the foreach loop in azurerm_virtual_network resource ?
│ Error: Unsupported attribute
│
│ on forloop.tf line 89, in resource "azurerm_virtual_network" "example":
│ 89: for_each = { for item in local.vnet_details : item.subnetName => item }
│
│ This object does not have an attribute named "subnetName".
2
Answers
The trailing dots on these lines could be the problem:
address_prefix = ["10.1.0.0./16"]
address_prefix = ["10.2.0.0./16"]
The reason for the error is that your
for_each
expression in theazurerm_virtual_network
resource is not structured properly. In particular, thelocal.vnet_details
list that you’re looping over does not have asubnetName
attribute for each element, since thevnet_details
list that you’ve created has a flattened structure that does not correspond to what thefor_each
expects.The main focus of my configuration will be to create a configuration that correctly defines and uses
local.vnet_details
for creating virtual networks andlocal.subnet_details
for creating subnets.My configuration:
Deployment Succeded: