Gokulnath Kumar
Gokulnath Kumar

Reputation: 169

How to get output for for_each loop condition within terraform?

I have a resource block with for_each loop condition and I wanted to output name and address_prefixes of the resource block.

main.tf:

resource "azurerm_subnet" "snets" {
    for_each = var.subnets
    name = each.key
    resource_group_name = azurerm_resource_group.rg.name
    virtual_network_name = azurerm_virtual_network.vnet.name
    address_prefixes = [each.value]
}

I have tried something like this, but it didn't worked.

output.tf

output "azurerm-subnet" {
    value = azurerm_subnet.snets.*.name
}

Error:

│ Error: Unsupported attribute
│
│   on output.tf line 2, in output "azurerm-subnet":
│    2:     value = azurerm_subnet.snets.*.name
│
│ This object does not have an attribute named "name".

Upvotes: 8

Views: 7461

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

This can most easily be accomplished with a list constructor and a for expression. We iterate through the map of exported attributes for the azurerm_subnet.snets and return the name value on each iteration:

output "azurerm_subnets" {
  value = [ for subnet in azurerm_subnet.snets : subnet.name ]
}

and the output azurerm_subnets will be a list(string) where each element is the subnet name.

Upvotes: 15

Related Questions