简体   繁体   English

如何在 terraform 中引用使用 for_each 创建的资源

[英]how to refer to resources created with for_each in terraform

This is what I'm trying to do.这就是我想要做的。 I have 3 NAT gateways deployed into separate AZs.我有 3 个 NAT 网关部署到不同的 AZ。 I am now trying to create 1 route table for my private subnets pointing to the NAT gateway.我现在正在尝试为指向 NAT 网关的私有子网创建 1 个路由表。 In terraform I have created the NAT Gateways using for_each.在 terraform 中,我使用 for_each 创建了 NAT 网关。 I am now trying to associate these NAT gateways with a private route table and getting an error because I created the NAT gateways using for_each.我现在尝试将这些 NAT 网关与私有路由表相关联并收到错误,因为我使用 for_each 创建了 NAT 网关。 Essentially, I am trying to refer to resources created with for_each in a resource that I do not need to use "for_each."本质上,我试图在不需要使用“for_each”的资源中引用使用 for_each 创建的资源。 Below is the code and error message.下面是代码和错误信息。 Any advice would be appreciated.任何意见,将不胜感激。

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错误

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.

The problem is that you are referencing each.key in the nat_gateway_id property of the "aws_route_table" "nat" resource without a for_each anywhere in that resource or sub-block.问题是您在"aws_route_table" "nat"资源的nat_gateway_id属性中引用each.key ,而在该资源或子块中的任何位置都没有for_each

Add a for_each to that resource and that should do the trick:将 for_each 添加到该资源,这应该可以解决问题:

Here is some sample code (untested):这是一些示例代码(未经测试):

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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM