在Terraform中,每个创建的公共子网都有一个NAT网关。我正在尝试为我的专用子网创建一个路由表,以指向NAT网关。在我的terraform代码中,我使用for_each创建了nat网关,并为我拥有的每个公共子网指定了一个NAT网关。在引用我的NAT网关的每个实例时遇到问题。任何意见将是有益的。以下是我的代码和错误:
resource "aws_nat_gateway" "main" {
for_each = aws_subnet.public
subnet_id = each.value.id
allocation_id = aws_eip.main[each.key].id
}
resource "aws_route_table" "nat" {
for_each = var.priv_subnet
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_nat_gateway.main[each.key].id
}
tags = {
Name = var.rt_tags_private
}
}
错误
Error: Invalid index
on vpc.tf line 71, in resource "aws_route_table" "nat":
71: gateway_id = aws_nat_gateway.main[each.key].id
|----------------
| aws_nat_gateway.main is object with 1 attribute "MainPubSub1"
| each.key is "0"
The given key does not identify an element in this collection value.
答案 0 :(得分:0)
我很难发布我认为可以解决此问题的内容,以防其他人遇到类似问题。
这可以通过chaining for_each between resources
解决resource "aws_nat_gateway" "main" {
for_each = aws_subnet.public
subnet_id = each.value.id
allocation_id = aws_eip.main[each.key].id
}
resource "aws_route_table" "nat" {
for_each = aws_nat_gateway.main
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = each.value.id
}
tags = {
Name = var.rt_tags_private
}
}
在表达式 aws_eip.main[each.key].id
中,each.key
部分采用 aws_subnet.public["key"]
的键。
我注意到据说已经找到了问题的解决方案,但是我很难分享。