Terraform NAT Gateway To Setup Route Table

3.2k views Asked by At

I'm trying to setup my private multiple NAT Gateways in my Route Table but I am confused on what I am missing. Can someone help me with my code on what I am missing?

This is my Route Table:

resource "aws_route_table" "private" {
  count                     = length(var.private_subnet_cidr_blocks)
  vpc_id                    = aws_vpc.main_vpc.id

  route {
    cidr_block              = "0.0.0.0/0"
    nat_gateway_id          = aws_nat_gateway.nat-gw[count.index].id
  }

  tags = {
    Name = "private-rtable-${count.index+1}"
  }
}

resource "aws_route_table_association" "private" {
  count                     = length(var.private_subnet_cidr_blocks)
  subnet_id                 = element(aws_subnet.private.*.id, count.index)
  route_table_id            = element(aws_route_table.private.*.id, count.index)
}

This is my NAT EIP and the NAT Gateway:

resource "aws_eip" "nat-eip" {
  count                     = length(data.aws_availability_zones.available.names)
  vpc                       = true
}

resource "aws_nat_gateway" "nat-gw" {
  count                     = length(data.aws_availability_zones.available.names)
  allocation_id             = element(aws_eip.nat-eip.*.id, count.index)
  subnet_id                 = element(aws_subnet.public.*.id, count.index)

  tags = {
    Name = "NAT-GW-${count.index+1}"
  }
}

I previously wanted to attach EACH NAT Gateway to my route table with a destination of 0.0.0.0/0 but that can't be done. Is there a way to have your NAT Gateways be high available in your architecture, or should you just attach one NAT Gateway? And if this was the case, what would I need to input to make it only attach one NAT Gateway in Terraform? Would appreciate any help.

UPDATE: For anyone who has questions on this scenario, I updated the code for others who are looking for answers.

1

There are 1 answers

1
Marcin On BEST ANSWER

The following is incorrect in aws_route_table.private:

  count                     = var.private_subnet_cidr_blocks

It should be:

  count                     = length(var.private_subnet_cidr_blocks)

Also your aws_route_table_association.private instead of:

route_table_id            = aws_route_table.private.id

there should be:

route_table_id            = element(aws_route_table.private.*.id, count.index)

The reason is that you will have as many route tables as your private subnets.