This is what I have so far, while I can pull a specific list or name using the local variables, I am having trouble transitioning this into the resource group. First, am I attempting this the right way? If not how can I iterate on the name for the subnet so that the subnets belonging to the respective vnet map are added?
variable "vnets" { default = [ { vnet_name = "test-vnet" address_space = "10.250.0.0" network_size = 16 subnets = [ { name = "first-subnet" network_security_group = "first-nsg" security_group_rules = [ { name = "first-sg" priority = 100 } ] }, { name = "second-subnet" network_security_group = "second-nsg" security_group_rules = [ { name = "second-sg" priority = 100 } ] } ] } ] } locals { subnet_names = { for vnet in var.vnets[*]: (vnet.vnet_name) => vnet.subnets[*].name } security_group_names = flatten(var.vnets[*].subnets[*].security_group_rules[*].name) } resource "azurerm_subnet" "subnets" { count = length(var.vnets) #??? name = locals.subnet_names[count.index].subnets.name resource_group_name = data.azurerm_resource_group.network_group.name virtual_network_name = azurerm_virtual_network.vnets.*.name address_prefixes = ["10.0.1.0/24"] }
I think the easiest would be to flatten your subnet_names
:
locals {
subnet_names = {
for vnet in var.vnets[*]:
(vnet.vnet_name) => vnet.subnets[*].name
}
security_group_names = flatten(var.vnets[*].subnets[*].security_group_rules[*].name)
# uniqueness of "${vnet}-${subnet}" pairs is assumed. it will not work
# if the pairs are not unique
subnet_names_flat = merge([
for vnet, subnets in local.subnet_names:
{
for subnet in subnets:
"${vnet}-${subnet}" => {name = vnet, subnet = subnet}
}
]...)
}
Which will result in subnet_names_flat
being:
{
"test-vnet-first-subnet" = {
"name" = "test-vnet"
"subnet" = "first-subnet"
}
"test-vnet-second-subnet" = {
"name" = "test-vnet"
"subnet" = "second-subnet"
}
}
Then your azurerm_subnet.subnets
could as below. However, I'm not able to verify correctness of your the azurerm_subnet
, thus you may need to change it further. But the idea is to iterate over local.subnet_names_flat
, which makes the for_each
very easy to use:
resource "azurerm_subnet" "subnets" {
for_each = local.subnet_names_flat
name = each.value.subnet
resource_group_name = data.azurerm_resource_group.network_group.name
virtual_network_name = each.value.vnet
address_prefixes = ["10.0.1.0/24"]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.