TravelingLex
TravelingLex

Reputation: 477

Calling specific for_each outputs

I'm just starting to use for_each loops and from what I understand for_each is different than count in the sense that count indexes numerically for outputs aws_transfer_key.transfer_key[1] vs for_each outputs aws_transfer_key.transfer_key["value"].

How do I call the output of a for_each value later on?

Upvotes: 2

Views: 898

Answers (2)

Martin Atkins
Martin Atkins

Reputation: 74099

A resource or data block with the count argument set appears in expressions as a list, which is why you can access its instances with [0], [1], etc.

Similarly, a resource or data block with the for_each argument set appears in expressions as a map, so you can access its instances with ["foo"], ["bar"], etc.

In both cases the collection is of objects conforming to the resource type schema, so you can follow that with .attribute syntax to access individual attributes.

So first take the resource type and name, aws_transfer_key.transfer_key, which is a map. Then ["value"] to access the instance you want from the map. Then .foo to access the "foo" attribute. All together, that's aws_transfer_key.transfer_key["value"].foo.

If you want to access all of the "foo" attributes across all of the instances, you can project the map of objects into a map of strings using a for expression:

{ for k, v in aws_transfer_key.transfer_key : k => v.foo }

Upvotes: 4

Elliot Pryde
Elliot Pryde

Reputation: 90

From the example here

resource "aws_security_group" "example" {
  name = "example" # can use expressions here

  dynamic "ingress" {
    for_each = var.service_ports
    content {
      from_port = ingress.value
      to_port   = ingress.value
      protocol  = "tcp"
    }
  }
}

You reference the name of the dynamic block, in this case it's an ingress.

Upvotes: 0

Related Questions