amazon-web-servicesforeachroutesterraformnat

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. I am now trying to create 1 route table for my private subnets pointing to the NAT gateway. In terraform I have created the NAT Gateways using for_each. 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. Essentially, I am trying to refer to resources created with for_each in a resource that I do not need to use "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.

Solution

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

    Add a for_each to that resource and that should do the trick:

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