Dave Michaels
Dave Michaels

Reputation: 937

Attaching private route table to NAT Gateway using for each terraform

In Terraform, I have a NAT gateway for every public subnet created. I am trying to create a route table for my private subnet to point to the NAT gateway. In my terraform code I created my nat gateways using for_each specifying for every public subnet I have, there needs to be a NAT gateway. I am getting an issue when referring to each instance of my NAT Gateway. Any advice would be helpful. Below is my code and error:

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

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.

Upvotes: 2

Views: 1820

Answers (1)

raulra08
raulra08

Reputation: 341

I tought of posting what I believe may fix this in case others have a similar issue.

This could be solved by 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
  }
}

In the expression aws_eip.main[each.key].id, the each.key part takes the key for aws_subnet.public["key"].

I noticed the solution to the problem was said to be found, however, I tought of sharing.

Upvotes: 0

Related Questions