Background:
Here is the map we are trying to iterate through:
cl_vnet = {
"xx.xx.1.0/24" = {
subnets = {
main = {
application = "app1",
addr_prefix = "xx.xx.1.0/25",
service_endpoints = [],
service_delegations = {}
},
backend = {
application = "app1",
addr_prefix = "xx.xx.1.128/25",
service_endpoints = [],
service_delegations = {}
}
}
}
}
In this block of code below, we are able to reference each subnet (main and backend) in the dynamic subnet block successfully.
resource "azurerm_virtual_network" "spoke-vnet" {
for_each = var.spoke_address_space
name = "${local.infra-prefix}-${local.region-code}-vnet"
location = var.location
address_space = [each.key]
resource_group_name = azurerm_resource_group.spoke-rg.name
tags = local.tags
dynamic "subnet" {
**for_each = each.value.subnets**
content {
name = "infra-${var.sz_app_group}-${subnet.value.application}-${var.sz_environment}-${local.region-code}-${subnet.key}-subnet"
address_prefix = subnet.value.addr_prefix
}
}
}
Result:
# module.cl-spoke.azurerm_virtual_network.spoke-vnet["xx.xx.xxx.0/24"] will be created
+ resource "azurerm_virtual_network" "spoke-vnet" {
+ address_space = [
+ "xx.xx.xxx.0/24",
]
+ id = (known after apply)
+ location = "northcentralus"
+ name = "infra-cl-dev-ncus-vnet"
+ resource_group_name = "infra-cl-dev-ncus-rg"
+ tags = {
+ "Application" = "cl"
+ "BillingCode" = "04070-74400"
+ "BusinessOwner" = "IT"
+ "Environment" = "dev"
+ "Group" = "Shared"
+ "ReferenceNumber" = "1234"
}
+ subnet {
+ address_prefix = "xx.xx.xxx.0/25"
+ id = (known after apply)
+ name = "infra-cl-app1-dev-ncus-main-subnet"
}
+ subnet {
+ address_prefix = "xx.xx.xxx.128/25"
+ id = (known after apply)
+ name = "infra-cl-app1-dev-ncus-backend-subnet"
}
}
Now we want to iterate through the subnets again this this resource:
resource "azurerm_subnet" "app-subnets" {
**for_each = var.spoke_address_space.value.subnets**
name = "infra-${each.value.application}-${var.sz_environment}-${local.region-code}-${each.key}-subnet"
resource_group_name = azurerm_virtual_network.spoke-vnet[var.spoke_address_space.key].resource_group_name
virtual_network_name = azurerm_virtual_network.spoke-vnet[var.spoke_address_space.key].name
address_prefix = each.value.addr_prefix
dynamic "delegation" {
for_each = each.value.service_delegations
content {
name = delegation.key
service_delegation {
name = delegation.value.name
actions = delegation.value.actions
}
}
}
}
Result:
Error: Missing map element
on .terraform\modules\cl-spoke\main.tf line 57, in resource "azurerm_subnet" "app-subnets":
57: for_each = var.spoke_address_space.value.subnets
|----------------
| var.spoke_address_space is map of object with 1 element
This map does not have an element with the key "value".
What is the proper way to iterate through this map in the second resource?