如何在for_each循环中检索当前项目的索引?

时间:2019-08-31 12:44:37

标签: terraform

我正在尝试在for_each循环中使用递增的rule_no创建入口规则:

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
    }
  }
  ...
}

错误是:

  

117:rule_no = 101 + ingress.index

     

该对象没有名为“ index”的属性。

是否有解决方法?

1 个答案:

答案 0 :(得分:1)

index替换key应该可以。来自documentation

  

key是当前元素的映射关键字或列表元素索引。如果for_each产生一个设定值,则keyvalue相同,因此不应使用。