我正在尝试为公共子网创建一个aws_route_table_association资源。公共子网的数量将在运行时确定,从而确定要创建的关联数。
在执行地形计划时,我的代码失败了。下面是我得到的源代码和错误。任何人都能就如何做到这一点提出建议。
// 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.我
发布于 2022-04-18 10:07:39
如果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
}https://stackoverflow.com/questions/71909695
复制相似问题