terraform 创建可以稍后使用的简单变量循环

terraform create simple loop of variable that can be used later

我是 Terraform 开发的新手,正在尝试创建可以稍后使用的简单变量循环,如下所示:

这对我来说非常有效,并按预期创建了两个子网。

variable "availability_zones" {
  description = "Available Availability Zones"
  type = "list"
  default = [ "us-east-1a", "us-east-1b" ]
}
variable "public_subnet_cidr" {
  description = "CIDR for Public Subnets"
  type = "list"
  default = [ "10.240.32.0/26", "10.240.32.64/26" ]

# Define Public Subnet
resource "aws_subnet" "public-subnets" {
  count = 2
  vpc_id = "${aws_vpc.default.id}"
  cidr_block = "${element(var.public_subnet_cidr, count.index)}"
  availability_zone = "${element(var.availability_zones, count.index)}"

  tags {
    Name = "${element(var.availability_zones, count.index)}_${element(var.public_subnet_cidr, count.index)}"
  }
}

但是在尝试将这些子网关联到默认路由时,我无法弄清楚如何从之前创建的那些子网中获取单个子网 ID。并以下面的代码结束。有没有办法获取 subnet.id 个单独的子网?

# Assign Default Public Route Table to Public Subnet
resource "aws_route_table_association" "default_public_route" {
  subnet_id = "${aws_subnet.public-subnets.id}"     <<-- This is the line I am trying to figure out
  route_table_id = "${aws_route_table.default_public_route_table.id}"
}

提前致谢。 山姆

您已经知道如何使用它了。这里有一个walk through可以帮到你。

resource "aws_route_table_association" "default_public_route" {
  count = 2
  subnet_id = "${element(aws_subnet.public-subnets.*.id, count.index)}"
  route_table_id = "${aws_route_table.default_public_route_table.id}"
}