aws_route_table_association 在运行时有多个子网 (AWS)

aws_route_table_association with multiple subnets at runtime (AWS)

我正在尝试为 public 个子网创建一个 aws_route_table_association 资源。 public 子网的数量将在运行时确定,因此要创建的关联数量。

在执行地形规划时,我的代码失败了。下面是我得到的源代码和错误。任何人都可以就实现此目标的方法提出建议。

//  required subnets and their configurations
variable "required_subnets" {
  description = "list of subnets required"
  default     = ["public-1a", "private-1a", "public-1b", "private-1b"]
}

#create public and provate subnets
resource "aws_subnet" "subnets" {
  count             = length(var.required_subnets)
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = lookup(var.subnet_conf[var.required_subnets[count.index]], "cidr")
  availability_zone = lookup(var.subnet_conf[var.required_subnets[count.index]], "availability_zone")

  # enable public ip addresses in public subnet
  map_public_ip_on_launch = false

  tags = {
    Name = var.required_subnets[count.index]
  }
}

//fetch reference to public subnets
data "aws_subnets" "public_subnets" {

  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.vpc.id]
  }

  tags = {
    Name = "public-*"
  }
}

#assosiate public route table with public subnet
resource "aws_route_table_association" "public" {
  count          = length(data.aws_subnets.public_subnets.ids)
  subnet_id      = data.aws_subnets.public_subnets.ids[count.index]
  route_table_id = aws_route_table.my_public_route_table.id
}

错误如下:

│ Error: Invalid count argument
│
│   on vpc.tf line 62, in resource "aws_route_table_association" "public":
│   62:   count          = length(data.aws_subnets.public_subnets.ids)
│
│ The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how    
│ many instances will be created. To work around this, use the -target argument to first apply only the resources that the   
│ count depends on.

如果required_subnets就是你所需要的,那么你的data.aws_subnets.public_subnets就没有理由了。此外,使用 for_each 而不是 count 会好得多,因为 for_each 不依赖于项目的顺序。因此,您可以简单地编写如下代码:

//  required subnets and their configurations
variable "required_subnets" {
  description = "list of subnets required"
  default     = ["public-1a", "private-1a", "public-1b", "private-1b"]
}

#create public and provate subnets
resource "aws_subnet" "subnets" {
  for_each          = toset(var.required_subnets)
  vpc_id            = aws_vpc.my_vpc.id
  cidr_block        = lookup(var.subnet_conf[each.key], "cidr")
  availability_zone = lookup(var.subnet_conf[each.key], "availability_zone")

  # enable public ip addresses in public subnet
  map_public_ip_on_launch = false

  tags = {
    Name = each.key
  }
}

#assosiate public route table with public subnet
resource "aws_route_table_association" "public" {
  for_each       = {for name, subnet in aws_subnet.subnets: name => subnet if length(regexall("public-", name)) > 0}   

  subnet_id      = each.value.id
  route_table_id = aws_route_table.my_public_route_table.id
}