这就是我正在努力做的事情。我有 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.
问题是您在
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
}
}
我尝试了十几种变体,发现这个有效......
我有一个地图变量...
variable workspace_maps {
description = "keys and values"
type = map(string)
default = {
"TEST Map1" = "TEST_Map1"
"TEST Map2" = "TEST_Map2"
"TEST Map3" = "TEST_Map3"
}
}
我用另一个来生成“envsuffix”,基于第三个,即环境。
在 main.tf ...
resource "fabric_workspace" "test_workspace" {
for_each = var.workspace_maps
display_name = "${each.key}${local.envsuffix}"
description = "Workspace testing"
capacity_id = var.fabric_capacity_id
}
然后通过 ..
引用每个“test_workspace”迭代resource "fabric_lakehouse" TEST_Lakehouse {
for_each = fabric_workspace.test_workspace
display_name = "${var.workspace_maps[each.key]}"
description = "TEST lakehouse${local.envsuffix}"
workspace_id = fabric_workspace.test_workspace[each.key].id
configuration = {
enable_schemas = true
}
}