这就是我想要做的。我将3个NAT网关部署到单独的可用区中。我现在正在尝试为指向NAT网关的专用子网创建1个路由表。在terraform中,我使用for_each创建了NAT网关。我现在尝试将这些NAT网关与专用路由表相关联,并收到错误消息,因为我使用for_each创建了NAT网关。本质上,我试图在不需要使用“ for_each”的资源中引用使用for_each创建的资源。下面是代码和错误消息。任何建议将不胜感激。
resource "aws_route_table" "nat" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main[each.key].id
}
tags = {
Name = "${var.vpc_tags}_PrivRT"
}
}
resource "aws_eip" "main" {
for_each = aws_subnet.public
vpc = true
lifecycle {
create_before_destroy = true
}
}
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_subnet" "public" {
for_each = var.pub_subnet
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value)
availability_zone = each.key
map_public_ip_on_launch = true
tags = {
Name = "PubSub-${each.key}"
}
}
错误
Error: Reference to "each" in context without for_each
on vpc.tf line 89, in resource "aws_route_table" "nat":
89: nat_gateway_id = aws_nat_gateway.main[each.key].id
The "each" object can be used only in "resource" blocks, and only when the
"for_each" argument is set.
答案 0 :(得分:2)
问题是您正在引用each.key
资源的nat_gateway_id
属性中的"aws_route_table" "nat"
,而该资源或子块中的任何地方都没有for_each
。
向该资源添加一个for_each,这应该可以解决问题:
以下是一些示例代码(未经测试):
resource "aws_route_table" "nat" {
for_each = var.pub_subnet
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main[each.key].id
}
}