amazon-web-services - 如何在 terraform 中引用使用 for_each 创建的资源
问题描述
这就是我想要做的。我有 3 个 NAT 网关部署到不同的 AZ。我现在正在尝试为指向 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
}
}
推荐阅读
- android - Firebase 默认通知颜色在三星中不可见
- java - 如何在应用程序顶部显示底部导航视图?
- python - 在 Pandas 中,如何按键中的每 N 行进行分组,保存一列的最后一个值并根据该“集合”中的所有行计算另一个值?
- node.js - 猫鼬:在 X 集合中创建新元素,在 Y 集合中更新另一个元素
- ruby-on-rails - 如何在 Windows 10 上将 MariaDB 与 Rails 一起使用?
- lua - 此表语法的含义
- javascript - 如何在页面完成加载时发出 AJAX 请求,由 window.location.href 触发
- machine-learning - 机器学习模型不适用于连续数据
- python-3.x - 如何设置 Anaconda 使其不会影响 MacOS 上的“homebrew python pip”和 Pyenv 等其他环境?
- amazon-web-services - 如何在没有开发端点的情况下测试 AWS Glue 代码