Chris Snow
Chris Snow

Reputation: 24588

How to retrieve index of current item in for_each loop?

I'm trying to create ingress rules with an incrementing rule_no inside a for_each loop:

resource "aws_default_network_acl" "default" {
  ...

  # allow client machine to have full access to all hosts

  ingress {
    protocol   = "-1"
    rule_no    = 100
    action     = "allow"
    cidr_block = "${var.primary_client_cidr_block}"
    from_port  = 0
    to_port    = 0
  }

  # additional_client_cidr_blocks example [ "x.x.x.x/32", "y.y.y.y/32", ... ] 
  # where x and y are replaced with actual IP addresses

  dynamic "ingress" {
    for_each = var.additional_client_cidr_blocks

    content {
      protocol   = "-1"
      rule_no    = 101 + ingress.index
      action     = "allow"
      cidr_block = ingress.value
      from_port  = 0
      to_port    = 0
    }
  }
  ...
}

The error is:

117: rule_no = 101 + ingress.index

This object does not have an attribute named "index".

Is there a workaround for this?

Upvotes: 1

Views: 7760

Answers (1)

user11391264
user11391264

Reputation:

Replacing index with key should work. From the documentation:

key is the map key or list element index for the current element. If the for_each exression produces a set value then key is identical to value and should not be used.

Upvotes: 2

Related Questions