Collecting one variable from resource with for_each

Hi @adyakin,

The [*] operator only applies to lists, but the for_each feature causes the resource to appear as a map. Therefore we need to use a for expression instead:

output "ip_addrs" {
  value = { for k, res in swm_ip_reservation.test1 : k => res.ip_addr}
}

In your case this would produce a map from hostname to IP address, perhaps like this:

{
  "host1.example.com" = "10.1.2.1"
  "host2.example.com" = "10.1.2.5"
}

If you want it to be a list, as would’ve been the case with count and a splat expression, you can write it slightly differently:

output "ip_addrs" {
  value = [ for res in swm_ip_reservation.test1 : res.ip_addr ]
}

Note that this list will end up being ordered by a lexical sort of the hostnames, because that’s the default ordering imposed by the for expression when projecting a map into a list.

1 Like