TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Internet Gateway, NAT & Route Tables

Internet Gateway, NAT & Route Tables

The subnets from the previous lesson are only "public" or "private" once routes say so. Route Tables and NAT explained the pieces:

  • an internet gateway attached to the VPC, and a public route table sending 0.0.0.0/0 to it, associated with the public subnets;
  • a NAT gateway (with an Elastic IP) in a public subnet, and private route tables sending 0.0.0.0/0 to it, so private workloads can reach the internet without being reachable from it.

The interesting decision is how many NAT gateways: one per zone survives the loss of a zone, but each costs a fixed hourly fee plus data processing (check current pricing). A common pattern is one shared NAT in dev and one per zone in prod, chosen by a variable.

The code

hcl
variable "nat_per_az" {
  type        = bool
  default     = false
  description = "true: one NAT gateway per zone (prod). false: one shared NAT gateway (dev)."
}

locals {
  # which zones get a NAT gateway
  nat_azs = var.nat_per_az ? var.azs : [var.azs[0]]
}

resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this.id
  }
}

resource "aws_route_table_association" "public" {
  for_each       = aws_subnet.public
  subnet_id      = each.value.id
  route_table_id = aws_route_table.public.id
}

resource "aws_eip" "nat" {
  for_each = toset(local.nat_azs)
  domain   = "vpc"
}

resource "aws_nat_gateway" "this" {
  for_each      = toset(local.nat_azs)
  allocation_id = aws_eip.nat[each.key].id
  subnet_id     = aws_subnet.public[each.key].id     # NAT lives in a PUBLIC subnet
  depends_on    = [aws_internet_gateway.this]        # AWS needs the IGW first (no reference shows it)
}

resource "aws_route_table" "private" {
  for_each = aws_subnet.private
  vpc_id   = aws_vpc.this.id
  route {
    cidr_block = "0.0.0.0/0"
    # same zone's NAT if there is one, otherwise the shared one
    nat_gateway_id = aws_nat_gateway.this[var.nat_per_az ? each.key : var.azs[0]].id
  }
}

resource "aws_route_table_association" "private" {
  for_each       = aws_subnet.private
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private[each.key].id
}

Notice the depends_on: the NAT gateway needs the internet gateway to exist, but nothing in its arguments refers to it. That is the textbook case for an explicit dependency (The Dependency Graph). for_each = aws_subnet.public iterates over a resource's instances directly: the keys are the zones.

dev vs prod, planned offline

The session assembles the VPC from the last lesson plus this routing, then plans it twice, once per NAT mode, and counts what each would create:

bash · try it yourself
mkdir net && cd net
cat > offline.tf <<'HCL'
provider "aws" {
  region                      = "eu-west-1"
  access_key                  = "offline"
  secret_key                  = "offline"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
HCL
cat > vpc.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
variable "cidr" {
  type    = string
  default = "10.20.0.0/16"
}
variable "azs" {
  type    = list(string)
  default = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
}
locals {
  az_index = { for i, az in var.azs : az => i }
}
resource "aws_vpc" "this" {
  cidr_block = var.cidr
}
resource "aws_subnet" "public" {
  for_each          = local.az_index
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(var.cidr, 8, each.value)
}
resource "aws_subnet" "private" {
  for_each          = local.az_index
  vpc_id            = aws_vpc.this.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(var.cidr, 4, each.value + 1)
}
HCL
cat > routing.tf <<'HCL'
variable "nat_per_az" {
  type    = bool
  default = false
}
locals {
  nat_azs = var.nat_per_az ? var.azs : [var.azs[0]]
}
resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id
}
resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this.id
  }
}
resource "aws_route_table_association" "public" {
  for_each       = aws_subnet.public
  subnet_id      = each.value.id
  route_table_id = aws_route_table.public.id
}
resource "aws_eip" "nat" {
  for_each = toset(local.nat_azs)
  domain   = "vpc"
}
resource "aws_nat_gateway" "this" {
  for_each      = toset(local.nat_azs)
  allocation_id = aws_eip.nat[each.key].id
  subnet_id     = aws_subnet.public[each.key].id
  depends_on    = [aws_internet_gateway.this]
}
resource "aws_route_table" "private" {
  for_each = aws_subnet.private
  vpc_id   = aws_vpc.this.id
  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.this[var.nat_per_az ? each.key : var.azs[0]].id
  }
}
resource "aws_route_table_association" "private" {
  for_each       = aws_subnet.private
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private[each.key].id
}
HCL
tofu init >/dev/null
for mode in false true; do
  echo "--- nat_per_az=$mode"
  tofu plan -var nat_per_az=$mode -out=tfplan | grep '^Plan:'
  tofu show -json tfplan | jq -r '[.resource_changes[].type] | group_by(.) | map("\(length) x \(.[0])") | .[]' | grep -E 'nat_gateway|eip|route_table
  


done
--- nat_per_az=false
Plan: 20 to add, 0 to change, 0 to destroy.
1 x aws_eip
1 x aws_nat_gateway
4 x aws_route_table
--- nat_per_az=true
Plan: 24 to add, 0 to change, 0 to destroy.
3 x aws_eip
3 x aws_nat_gateway
4 x aws_route_table

Same code, two shapes: the variable decides between 1 and 3 NAT gateways (and Elastic IPs), while the route tables stay the same four (one public, one private per zone), so switching dev to the per-zone layout later only adds gateways and changes routes.

Cheaper and safer alternatives

  • VPC endpoints: S3 and DynamoDB gateway endpoints are free and keep that traffic off the NAT gateway (aws_vpc_endpoint with vpc_endpoint_type = "Gateway", associated with the private route tables). Interface endpoints for ECR, STS, CloudWatch Logs let private EKS nodes pull images without internet access at all.
  • IPv6 with an egress-only internet gateway avoids NAT for IPv6 traffic.
  • In dev, some teams skip NAT entirely and run workloads in public subnets with strict security groups; acceptable for throw-away environments only.

Test yourself

In which kind of subnet must a NAT gateway be placed?

  1. A private subnet
  2. A public subnet with a route to the internet gateway
  3. Any subnet
  4. Its own dedicated VPC

Why does aws_nat_gateway have depends_on = [aws_internet_gateway.this]?

  1. To make the plan shorter
  2. The NAT gateway needs the IGW, but none of its arguments reference it, so the graph wouldn't know
  3. depends_on is required on every resource
  4. To avoid a cycle

What is the trade-off of one NAT gateway per availability zone?

  1. Slower DNS
  2. Higher fixed cost, but private subnets keep internet access when one zone fails
  3. It disables IPv6
  4. None