如何使用地形中的数据源获得每个AZ的唯一AWS子网ID



VPC需要连接中转网关,代码:

resource "aws_ec2_transit_gateway_vpc_attachment" "vpc_live" {
subnet_ids         = toset(data.aws_subnets.vpc_live.ids)
transit_gateway_id = var.tgw_id
vpc_id             = var.vpc_id
}

数据源:

data "aws_subnets" "vpc_live" {
filter {
name   = "vpc-id"
values = [var.vpc_id]
}
}

错误:

Error: updating EC2 Transit Gateway VPC Attachment (tgw-attach-xxxxxxxxxxxxxxx): InvalidParameterValue: AddSubnets values count greater than region availability zones
│   status code: 400, request id: dnc3c5d-8927-029c-9fd5-311c3c5b5046
│
│   with aws_ec2_transit_gateway_vpc_attachment.vpc_live,
│   on main.tf line 7, in resource "aws_ec2_transit_gateway_vpc_attachment" "vpc_live":
│    7: resource "aws_ec2_transit_gateway_vpc_attachment" "vpc_live" {

据我所知,每个可用区域(AZ(只需要一个子网id。我一直在他们的GitHub问题StackOverflow中到处搜索,但我想知道是否没有人面临过这个主要问题。

所以我的问题是,我如何过滤我的数据源,使其每个AZ只返回1个子网ID?

好吧,这很容易:

首先,将所有可用区域连接到每个子网:

data "aws_subnet" "vpc_live" {
for_each = toset(data.aws_subnets.vpc_live.ids)
id       = each.key
}

第二,反其道而行之。获取属于这些AZ:的所有子网

{ for s in data.aws_subnet.vpc_live : s.availability_zone => s.id... }

最后,从所有AZ:中选择索引上的第一个子网

resource "aws_ec2_transit_gateway_vpc_attachment" "vpc_live" {
subnet_ids         = [for subnet_ids in { for s in data.aws_subnet.ids : s.availability_zone => s.id... } : subnet_ids[0]]
transit_gateway_id = var.tgw_id
vpc_id             = var.vpc_id
}

我在系统上运行了代码,并检查了输出:

subnets_ids = [
+ "subnet-xxxx123",
+ "subnet-xxxx456",
+ "subnet-xxxx789",
]

最新更新