我正在尝试为公共子网创建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.
如果您只需要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
}