Building a VPC by hand: public and private subnets, route tables and NAT
One VPC across two availability zones in Terraform, with public and private subnets, route tables, and three ways to get the private side online: a NAT gateway, a NAT instance or VPC endpoints, with Mumbai prices for each.
My own blog runs in the default VPC. Every subnet in it is public, the one EC2 instance has an Elastic IP, and the Terraform for the network is mostly aws_default_vpc and aws_default_subnet resources that I imported after the fact. For one box that is fine. For anything with a database or a few services, you want a VPC where the private parts really are private, and you want to know what it costs to let them reach the internet.
In this blog we will build that VPC by hand in Terraform: one VPC across two availability zones, a public and a private subnet in each, route tables, and then the part that surprises people on the bill, which is NAT. Level is intermediate. You should be able to run terraform plan and apply (see Terraform hands-on: your first EC2 instance with plan and apply) and have an AWS account set up as in Setting up a new AWS account safely.
I used Terraform 1.17.1 and the AWS provider 6.73.0. All prices are for ap-south-1 (Mumbai), taken from the AWS Price List API on 19 November 2026. I ran terraform fmt and terraform validate on every file below, but I did not apply it against an account for this post.
What we are building
VPC 10.20.0.0/16 (ap-south-1)
|
+-- ap-south-1a
| public 10.20.0.0/24 -> route table "public" -> internet gateway
| private 10.20.10.0/24 -> route table "private-a" -> NAT (or nothing)
|
+-- ap-south-1b
public 10.20.1.0/24 -> route table "public" -> internet gateway
private 10.20.11.0/24 -> route table "private-b" -> NAT (or nothing)
A subnet is "public" only because its route table has a 0.0.0.0/0 route to an internet gateway. That's the whole definition. There's no checkbox called public. A private subnet is one whose route table has no such route, so instances in it can't be reached from the internet and, by default, can't reach out either.
The VPC and subnets
First, the variables. nat_mode picks how the private subnets get out, and we will come to it in a bit.
variable "region" {
type = string
default = "ap-south-1"
}
variable "name" {
type = string
default = "shorty"
}
variable "vpc_cidr" {
type = string
default = "10.20.0.0/16"
}
variable "azs" {
type = list(string)
default = ["ap-south-1a", "ap-south-1b"]
}
variable "nat_mode" {
type = string
default = "instance"
validation {
condition = contains(["gateway", "instance", "none"], var.nat_mode)
error_message = "nat_mode must be gateway, instance or none."
}
}
variable "ssm_endpoints" {
type = bool
default = false
}
Then the VPC, the internet gateway and four subnets. I use cidrsubnet so I don't type CIDRs by hand. cidrsubnet("10.20.0.0/16", 8, 0) is 10.20.0.0/24, and with an offset of 10 the private ones land on 10.20.10.0/24 and 10.20.11.0/24. I checked those in terraform console before trusting them, it takes ten seconds only.
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = var.name }
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = { Name = var.name }
}
resource "aws_subnet" "public" {
count = length(var.azs)
vpc_id = aws_vpc.main.id
availability_zone = var.azs[count.index]
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index)
map_public_ip_on_launch = true
tags = { Name = "${var.name}-public-${var.azs[count.index]}" }
}
resource "aws_subnet" "private" {
count = length(var.azs)
vpc_id = aws_vpc.main.id
availability_zone = var.azs[count.index]
cidr_block = cidrsubnet(var.vpc_cidr, 8, count.index + 10)
tags = { Name = "${var.name}-private-${var.azs[count.index]}" }
}
Keep enable_dns_hostnames on. Interface endpoints with private DNS don't work without it, and you will forget that later.
Route tables
One public route table shared by both public subnets. The private side gets one route table per AZ. With a single NAT both point at the same place, but when you later add a second NAT for the other AZ you only change a route, not the layout.
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
tags = { Name = "${var.name}-public" }
}
resource "aws_route" "public_internet" {
route_table_id = aws_route_table.public.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
resource "aws_route_table_association" "public" {
count = length(var.azs)
subnet_id = aws_subnet.public[count.index].id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table" "private" {
count = length(var.azs)
vpc_id = aws_vpc.main.id
tags = { Name = "${var.name}-private-${var.azs[count.index]}" }
}
resource "aws_route_table_association" "private" {
count = length(var.azs)
subnet_id = aws_subnet.private[count.index].id
route_table_id = aws_route_table.private[count.index].id
}
I write routes as separate aws_route resources instead of inline route blocks. Mixing the two styles on one table makes Terraform fight itself, and separate resources are easier to add with count.
Getting the private subnets online
Your app in the private subnet still needs to pull images, call an API, send mail through SES or talk to S3. There are three ways. Here is what each one costs per month in Mumbai, using 730 hours.
| Option | Fixed per month | Per GB | Notes |
|---|---|---|---|
| NAT gateway, one AZ | $40.88 + $3.65 public IPv4 = $44.53 | $0.056 processed | managed, scales, one AZ is a single point of failure |
| NAT gateway, one per AZ | $89.06 | $0.056 processed | what most guides tell you to do |
| NAT instance, t4g.nano | $2.04 + $3.65 IPv4 + $0.73 for 8 GB gp3 = $6.42 | none | you patch it, it is one small box |
| S3 gateway endpoint | $0 | $0 | only S3 (and DynamoDB has one too) |
| Interface endpoints for SSM (3 x 2 AZs) | $56.94 | $0.01 | each endpoint is $0.013 an hour per AZ |
Internet data transfer out is billed on top in all of the NAT cases, so it doesn't change the comparison much.
Two things in that table actually caught me. The public IPv4 charge ($0.005 an hour) is easy to miss because it shows up under VPC, not EC2. And the interface endpoints, which people add "to save NAT costs", cost more than a NAT gateway once you need a few of them in two AZs. They are worth it for security reasons sometimes. They are rarely worth it for money.
Option 1: NAT gateway
The managed way. An Elastic IP, a NAT gateway in a public subnet, and a default route from every private route table.
locals {
use_gateway = var.nat_mode == "gateway"
use_instance = var.nat_mode == "instance"
}
resource "aws_eip" "nat" {
count = local.use_gateway ? 1 : 0
domain = "vpc"
tags = { Name = "${var.name}-nat" }
}
resource "aws_nat_gateway" "main" {
count = local.use_gateway ? 1 : 0
allocation_id = aws_eip.nat[0].id
subnet_id = aws_subnet.public[0].id
tags = { Name = var.name }
depends_on = [aws_internet_gateway.main]
}
resource "aws_route" "private_nat_gateway" {
count = local.use_gateway ? length(var.azs) : 0
route_table_id = aws_route_table.private[count.index].id
destination_cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main[0].id
}
While checking the provider schema I noticed aws_nat_gateway in 6.x has an availability_mode argument, for the newer regional NAT gateway that spans AZs. The Price List shows the same $0.056 hourly and per GB rate for it in Mumbai. I stuck with the zonal one here because it's what most existing setups have, but check the NAT gateway pricing page before you pick, how the regional one bills per AZ is the part I'd read twice.
Option 2: NAT instance
This is just an EC2 instance with IP forwarding on and source/destination check off. AWS doesn't publish a NAT AMI for Amazon Linux 2023, so we build it from Amazon Linux 2023 on Graviton.
data "aws_ssm_parameter" "al2023_arm64" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64"
}
resource "aws_security_group" "nat" {
count = local.use_instance ? 1 : 0
name = "${var.name}-nat"
description = "Traffic from the private subnets to the NAT instance"
vpc_id = aws_vpc.main.id
ingress {
description = "Anything from inside the VPC"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = [var.vpc_cidr]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "nat" {
count = local.use_instance ? 1 : 0
ami = data.aws_ssm_parameter.al2023_arm64.value
instance_type = "t4g.nano"
subnet_id = aws_subnet.public[0].id
vpc_security_group_ids = [aws_security_group.nat[0].id]
source_dest_check = false
metadata_options {
http_tokens = "required"
}
user_data = <<-EOT
#!/bin/bash
set -euo pipefail
dnf install -y iptables-services
systemctl enable --now iptables
echo "net.ipv4.ip_forward = 1" > /etc/sysctl.d/90-nat.conf
sysctl -p /etc/sysctl.d/90-nat.conf
IFACE=$(ip route show default | awk '{print $5; exit}')
iptables -t nat -A POSTROUTING -o "$IFACE" -s ${var.vpc_cidr} -j MASQUERADE
iptables -F FORWARD
service iptables save
EOT
tags = { Name = "${var.name}-nat" }
lifecycle {
ignore_changes = [ami]
}
}
resource "aws_route" "private_nat_instance" {
count = local.use_instance ? length(var.azs) : 0
route_table_id = aws_route_table.private[count.index].id
destination_cidr_block = "0.0.0.0/0"
network_interface_id = aws_instance.nat[0].primary_network_interface_id
}
The order in that user data matters. iptables-services ships default rules that REJECT everything in the FORWARD chain. If you add your MASQUERADE rule first and start the service after, what happens is the service loads its defaults over yours and nothing gets forwarded. So: start the service, add the NAT rule, flush FORWARD, then save. This part trips people up more than anything else about NAT instances.
ignore_changes = [ami] is there because the SSM parameter moves every time Amazon publishes a new image, and I don't want a plan to replace my NAT box on a random Tuesday. Patch it with dnf upgrade through SSM instead, the same way I do on the blog host (see Running a Docker host on EC2 with SSM instead of SSH).
The honest downside. It's one instance in one AZ. If it dies, private subnets lose the internet until you fix it. For a side project or a dev account I take that deal every time at $6 a month. For production with real traffic I'd pay for the gateway.
Option 3: endpoints, and no NAT at all
If the private side only needs S3, you may not need NAT itself. A gateway endpoint for S3 is free and is just a route added to the route tables.
resource "aws_vpc_endpoint" "s3" {
vpc_id = aws_vpc.main.id
service_name = "com.amazonaws.${var.region}.s3"
vpc_endpoint_type = "Gateway"
route_table_ids = aws_route_table.private[*].id
tags = { Name = "${var.name}-s3" }
}
I add this one to every VPC, even with a NAT gateway. S3 traffic that goes through NAT pays the $0.056 per GB processing charge. Through the endpoint it pays nothing. A nightly backup to S3 like the one in Nightly MySQL and content backups to S3 with a systemd timer is exactly the kind of traffic you want on the endpoint.
For other services you need interface endpoints. Here are the ones Session Manager uses. The SSM docs still list ec2messages, though agents from 3.3.40 onwards prefer ssmmessages, so you may get away with two.
resource "aws_security_group" "endpoints" {
count = var.ssm_endpoints ? 1 : 0
name = "${var.name}-endpoints"
description = "HTTPS from the VPC to interface endpoints"
vpc_id = aws_vpc.main.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.vpc_cidr]
}
}
resource "aws_vpc_endpoint" "ssm" {
for_each = var.ssm_endpoints ? toset(["ssm", "ssmmessages", "ec2messages"]) : toset([])
vpc_id = aws_vpc.main.id
service_name = "com.amazonaws.${var.region}.${each.key}"
vpc_endpoint_type = "Interface"
subnet_ids = aws_subnet.private[*].id
security_group_ids = [aws_security_group.endpoints[0].id]
private_dns_enabled = true
tags = { Name = "${var.name}-${each.key}" }
}
Running it
The provider block and outputs are in the full code. Then pick a mode.
terraform init
terraform plan -var nat_mode=instance
terraform apply -var nat_mode=instance
To switch to a NAT gateway later, run apply with -var nat_mode=gateway. Terraform removes the instance routes and adds the gateway ones. There is a short gap with no route while it does that, so don't do it in the middle of a deploy.
Checking the routes
After apply I always look at the route tables from the CLI instead of trusting the console. This lists every route table in the VPC with its routes and targets.
VPC_ID=$(terraform output -raw vpc_id)
aws ec2 describe-route-tables \
--filters Name=vpc-id,Values="$VPC_ID" \
--query 'RouteTables[].{name: Tags[?Key==`Name`]|[0].Value, routes: Routes[].[DestinationCidrBlock || DestinationPrefixListId, GatewayId || NatGatewayId || NetworkInterfaceId]}' \
--output json
The list of routes in each private table are short, three of them: the local 10.20.0.0/16, a pl- prefix list for the S3 endpoint, and 0.0.0.0/0 to the NAT. If the last one says blackhole, the NAT instance or gateway it pointed to is gone.
Then from instance in a private subnet, through Session Manager, run curl -s https://checkip.amazonaws.com. It should print the public IP of the NAT, not anything else. If it hangs, look at the NAT instance's source/dest check first. That's nearly always the one.
Why I still run the blog in the default VPC
Somebody will definitely ask. It's one t3.small with an Elastic IP, Caddy in front and the database in a container on the same box, so there's no private tier to protect. Moving it into a VPC like this would add a NAT bill for no gain. The day the database moves to its own instance or RDS, it goes in a private subnet and gets the S3 endpoint plus a NAT instance.