如何在terraform中过滤aws子网



我正在将一个定制的部署基础设施移植到terraform。在那个自定义代码库中,有一些东西说-从默认区域vpc中获取所有可用的子网,但只获取那些有20个或更多可用IPv4地址的子网。

所以我在试验这段代码

data "aws_vpc" "main" {
default = true
}
data "aws_subnets" "vpcsubnets" {
filter {
name   = "vpc-id"
values = [data.aws_vpc.main.id]
}
filter {
name   = "default-for-az"
values = [true]
}
filter {
name   = "state"
values = ["available"]
}
}
output "ids2" {
value = {
for k, v in data.aws_subnets.vpcsubnets : k => v if v.available_ip_address_count > 20
}
}

但是我得到了这样的错误

Error: Invalid reference
│ 
│   on main.tf line 51, in output "ids2":
│   51:     for k, vid in data.aws_subnets.vpcsubnets : k => v if v.available_ip_address_count > 20
│ 
│ A reference to a resource type must be followed by at least one attribute access, specifying the resource name.

使用Terraform 1.0.8和aws provider 3.62

这里需要一个额外的中间步骤。可用子网的完整列表在属性data.aws_subnets.vpcsubnets.ids中可用,但属性available_ip_address_count只能从aws_subnet数据中可用。您需要检索中间数据中每个可用子网的信息:

data "aws_subnet" "vpcsubnet" {
for_each = toset(data.aws_subnets.vpcsubnets.ids)
id = each.value
}

现在该属性在命名空间data.aws_subnet.vpcsubnet["<id>"].available_ip_address_count中可用。您可以轻松地对output进行一个小更新:

output "ids2" {
value = {
for id, attributes in data.aws_subnet.vpcsubnet : id => attributes if attributes.available_ip_address_count > 20
}
}

为清晰起见,我还重命名了临时lambda变量。

可以了

data "aws_vpc" "main" {
default = true
}
data "aws_subnets" "vpcsubnets" {
filter {
name   = "vpc-id"
values = [data.aws_vpc.main.id]
}
filter {
name   = "default-for-az"
values = [true]
}
filter {
name   = "state"
values = ["available"]
}
}
data "aws_subnet" "vpcsubnet" {
for_each = { for index, subnetid in data.aws_subnets.vpcsubnets.ids : index => subnetid }
id       = each.value
}
output "ids2" {
value = [
for v in data.aws_subnet.vpcsubnet : v if v.available_ip_address_count > 20
]
}

最新更新