for_each 并计算 Terraform 中的表达式

for_each and count expressions in Terraform

我正在尝试研究 Terraform。我有子网,它们是用“for_each”表达式创建的。

variable "privateSubnetCIDR" {
  type = list(string)
  default = ["10.0.10.0/24","10.0.20.0/24"]
}
resource "aws_subnet" "privatesubnet" {
  for_each                = toset(var.privateSubnetCIDR)
  cidr_block              = each.key
  vpc_id                  = aws_vpc.dev_vpc.id
  map_public_ip_on_launch = false
  availability_zone       = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
  tags = {
    name        = "${var.environment}-privatesubnet-${index(var.privateSubnetCIDR, each.key) + 1}"
    AZ          = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
    Environment = "${var.environment}-privatesubnet"
  }
}

我还有 NAT 路由表,它使用“计数”。

resource "aws_route_table" "nat_routetable" {
  vpc_id = aws_vpc.dev_vpc.id
  count  = length(var.publicSubnetCIDR)
  route {
    cidr_block = var.route_cidr
    gateway_id = aws_nat_gateway.nat-gateway[count.index].id
  }
  depends_on = [aws_nat_gateway.nat-gateway]
}
resource "aws_route_table_association" "nat_routeTableAssociation" {
  count          = length(var.privateSubnetCIDR)
  route_table_id = aws_route_table.nat_routetable[count.index].id
  subnet_id      = aws_subnet.privatesubnet[count.index].id
}

terraform plan 后最后一个字符串出现错误。

│ Error: Invalid index
│ 
│   on modules/network/subnets.tf line 91, in resource "aws_route_table_association" "nat_routeTableAssociation":
│   91:   subnet_id      = aws_subnet.privatesubnet[count.index].id
│     ├────────────────
│     │ aws_subnet.privatesubnet is object with 2 attributes
│     │ count.index is 0
│ 
│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name,
│ not by numeric index.

如果我在子网定义中使用“count”,一切正常。但是有什么办法可以在子网定义中使用“for_each”而在route_table定义中使用“计数”吗?

你可以做到,是的。不过你需要通过中介var.privateSubnetCIDR:

aws_subnet.privatesubnet[var.privateSubnetCIDR[count.index]].id

但那时你也应该在 aws_route_table_association 上使用 for_each