I am using a for_each statement to create several subnets in an Azure Virtual network. This seems to work without any problems, but when I then use azurerm_subnet.acc_subnets[“subnetname”].id to retrieve the subnet ids to use later on for subnet_association, the values I get are not consistent. Of the 7 subnets I create the 1st and 5th subnet return the correct value, but the other 5 return the correct value MINUS the “/” in front, which might lead to errors in the subnet association part of the code
[]
resource “azurerm_subnet” “acc_subnets” {
for_each = var.environment == “acc” ? local.subnetAcc : {} #this creates the acceptance subnets, specified earlier under locals, if the environment variable is acc
name = each.key
resource_group_name = data.azurerm_resource_group.getAzureVnetResourceGroup.name
virtual_network_name = data.azurerm_virtual_network.getVirtualNetwork.name
address_prefixes = [each.value]
depends_on = [ azurerm_network_security_group.subnetNSG ]
}
data “azurerm_subnet” “subnet2” {
name = “subnet2”
resource_group_name = data.azurerm_resource_group.getAzureVnetResourceGroup.name
virtual_network_name = data.azurerm_virtual_network.getVirtualNetwork.name
}
output “data-subnet” { #works, has /
value = data.azurerm_subnet.subnet2.id
}
output “resource-subnet” { #does not work, does not have /
value =azurerm_subnet.acc_subnets[“subnet2”].id
}
I have tried setting the AzureRM provider to the latest version and a lot of other troubleshooting to see where the issue lies, by using output blocks I can see it seems to be caused by something in the for_each block, If I use a separate data block to get the subnet_id I get the correct form (with “/” in front), but if I use a output block to get the subnet id directly from the resource block I get varied results.
I can of course circumvent this issue by creating each subnet using a separate resource block, but I would really like to understand what I am doing wrong here. Any help would be much appreciated.