在Terraform中,我为创建的每个公共子网都有一个NAT网关。我正在尝试为我的私有子网创建一个指向NAT网关的路由表。在我的地形代码中,我使用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.
如果其他人也有类似的问题,我很难发布我认为可以解决这个问题的内容。
这可以通过在资源之间链接for_each来解决
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"]
的密钥。
我注意到问题的解决方案据说已经找到了,然而,我很难分享。