【问题标题】:Attaching private route table to NAT Gateway using for each terraform使用每个 terraform 将私有路由表附加到 NAT 网关
【发布时间】:2020-12-02 15:36:09
【问题描述】:

在 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.

【问题讨论】:

  • 您的 NAT 网关与公共子网相关联,但您试图通过迭代私有子网来引用它们。您需要根据可用区确定哪个公共子网对应于哪个私有子网。我认为您无法以自动化方式执行此操作(尽管我没有查看 0.13 中的数据提供程序)。
  • 搞定了!谢谢!
  • 如果您回答了自己的问题并展示了您所做的事情,可能对其他人有用。

标签: amazon-web-services terraform terraform-provider-aws nat


【解决方案1】:

如果其他人遇到类似问题,我会发布我认为可以解决此问题的内容。

这可以通过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"] 的键。

我注意到问题的解决方案据说找到了,但是我很难分享。

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2019-01-15
    • 2017-10-02
    • 2021-01-08
    • 2021-02-25
    • 2020-11-27
    相关资源
    最近更新 更多