How to reference module output where module is using for_each

Hi There

Been trying to get this working but still haven’t managed too.

I have a module called subnet.
The module has an output like this.

output “subnet_id” {
value = azurerm_subnet.azure-subnet.id
}

I am invoking the module like this. The variable subnet_addresses is of type map.

module “subnet” {
for_each = var.subnet_addresses
source = “”
subnet_name = each.key
address_prefixes = each.value
}

I have a tfvars file that looks like

subnet_addresses = {
AzureSubnetAppGateway = “10.0.0.0”
AzureSubnetWeb = “10.0.0.0”
AzureSubnetData = “10.0.0.0” (not actual subnet values)
}

When trying to reference a particular subnet e.g inside an app gateway, it’s not working. let’s say i was trying to reference the subnet “AzureSubnetWeb” and get it’s ID.

frontend_ip_configuration {
name = local.frontend_ip_configuration_name
subnet_id = module.subnet[1].subnet_id
private_ip_address_allocation = “dynamic”
}

the error i am getting is

Error: Invalid index

48: subnet_id = module.subnet[1].subnet_id
|----------------
| module.subnet is object with 3 attributes
The given key does not identify an element in this collection value.

You are trying to access the subnet module by number using [1] which is fine if you are using the count option to produce multiple instances. For for_each you need to use the name rather than a number [“xxx”] which is the key of the map you are passing in (so “AzureSubnetWeb” for example).

1 Like

@stuart-c you are the man.
Thanks sir. this has worked. I referenced using the key of the map like you said and the apply went through fine.

Thanks again