如何在Terraform中引用for_each创建的资源

时间:2020-01-22 17:43:08

标签: terraform

我通过在Terraform中使用for_each如下创建了多个[私有/公共]子网

resource "aws_subnet" "public" {
  for_each = toset(data.aws_availability_zones.azs.names)
  vpc_id = aws_vpc.vpc.id
  cidr_block = cidrsubnet(var.private_ranges,1 ,index(data.aws_availability_zones.azs.names, each.value))
  availability_zone = each.value
  map_public_ip_on_launch = true
  tags = merge(local.common_tags, map("Name", join("-", [local.prefix, index(data.aws_availability_zones.azs.names,each.value )]),
  "Availibility Zone", each.value, "Type", "Public"))

  lifecycle {
    prevent_destroy = false
  }
}

resource "aws_subnet" "private" {
  for_each = toset(data.aws_availability_zones.azs.names)
  vpc_id = aws_vpc.vpc.id
  cidr_block = cidrsubnet(var.private_ranges,1 ,index(data.aws_availability_zones.azs.names, each.value))
  availability_zone = each.value
  tags = merge(local.common_tags, map("Name", join("-", [local.prefix, index(data.aws_availability_zones.azs.names,each.value )]),
  "Availibility Zone", each.value, "Type", "Private"))

  lifecycle {
    prevent_destroy = false
  }
}

我需要在其他资源aws_default_network_acl中引用这些子网

resource "aws_default_network_acl" "default" {
  default_network_acl_id = aws_vpc.vpc.default_network_acl_id
  subnet_ids = <can you tell me how to reference the subnet ids here>
........

1 个答案:

答案 0 :(得分:0)

我使用以下解决方案做到了

subnet_ids = concat([for subnet in aws_subnet.private: subnet.id], [for subnet in aws_subnet.public: subnet.id])