A VPC on AWS

Intermediate · 23 min

Build an AWS network in Terraform: plan CIDR ranges with cidrsubnet, then VPC, subnets, gateways and routes with for_each, and what NAT and public IPv4 cost.

Before thiscount and for_each

Anton Putra · 23 min

A VPC on AWS

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Anton PutraReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Plan addresses before writing HCL: cidrsubnet adds bits to a prefix and picks the netnum-th block, and a subnet's range cannot be changed in place.
  • A subnet is public because its route table sends 0.0.0.0/0 to an internet gateway; private subnets route to a NAT gateway instead.
  • Key for_each by availability zone name, not list position, so adding a zone does not renumber the others.
  • One NAT gateway per zone is resilient and costs more; a single_nat_gateway variable makes it a deliberate trade. Public IPv4 addresses are billed per hour.

Every real AWS project starts with a network

The networking lesson in devops explained what a VPC, a subnet and a security group are. This lesson is the part where you write it down in Terraform, and discover that “a VPC” is about a dozen resources that have to agree with each other: the VPC, the subnets, an internet gateway, route tables and their associations, NAT, maybe endpoints. Get the CIDR plan wrong and you cannot fix it without rebuilding everything inside, because a subnet’s range cannot be changed in place.

So the first job is not HCL at all. It is a table of addresses.

Plan the addresses first

Terraform’s cidrsubnet(prefix, newbits, netnum) carves a smaller block out of a bigger one: it adds newbits bits to the prefix and picks the netnum-th block. A /16 plus 8 new bits gives /24 subnets, and netnum counts from zero. I did not have Terraform to call it, so I rewrote its arithmetic with Python’s ipaddress module and used it to lay out three tiers across three availability zones. The function is my reimplementation of the documented behaviour, and the error line is my own wording, not Terraform’s:

$ python3 -I cidr.py
public    eu-west-1a  10.0.0.0/24      usable hosts=251
public    eu-west-1b  10.0.1.0/24      usable hosts=251
public    eu-west-1c  10.0.2.0/24      usable hosts=251
private   eu-west-1a  10.0.10.0/24     usable hosts=251
private   eu-west-1b  10.0.11.0/24     usable hosts=251
private   eu-west-1c  10.0.12.0/24     usable hosts=251
database  eu-west-1a  10.0.20.0/24     usable hosts=251
database  eu-west-1b  10.0.21.0/24     usable hosts=251
database  eu-west-1c  10.0.22.0/24     usable hosts=251
overlaps: False
all inside vpc: True
error: prefix extension of 4 bits does not accommodate netnum 16

The “usable hosts” count is the block size minus five, because AWS reserves five addresses in every subnet. The gaps between 2 and 10, and 12 and 20, are deliberate headroom: add a fourth zone or a new tier later without renumbering. The last line shows what happens when netnum does not fit in the new bits. Choose the VPC range so it does not overlap with other VPCs or your office network, because peering and VPNs need ranges that are distinct.

The resources

This is written from the AWS provider documentation, and I did not run it, since Terraform and an AWS account are not available here. It builds the public and private tiers and leaves the database tier as an exercise:

data "aws_availability_zones" "available" { state = "available" }

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 3)
}

resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true
  tags                 = { Name = "main" }
}

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

resource "aws_subnet" "public" {
  for_each                = { for i, az in local.azs : az => i }
  vpc_id                  = aws_vpc.main.id
  availability_zone       = each.key
  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value)
  map_public_ip_on_launch = false
  tags                    = { Name = "public-${each.key}" }
}

resource "aws_subnet" "private" {
  for_each          = { for i, az in local.azs : az => i }
  vpc_id            = aws_vpc.main.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, 10 + each.value)
  tags              = { Name = "private-${each.key}" }
}

resource "aws_eip" "nat" {
  for_each = aws_subnet.public
  domain   = "vpc"
}

resource "aws_nat_gateway" "main" {
  for_each      = aws_subnet.public
  allocation_id = aws_eip.nat[each.key].id
  subnet_id     = each.value.id
  depends_on    = [aws_internet_gateway.main]
}

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

resource "aws_route_table" "private" {
  for_each = aws_subnet.private
  vpc_id   = aws_vpc.main.id
  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.main[each.key].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_route_table_association" "private" {
  for_each       = aws_subnet.private
  subnet_id      = each.value.id
  route_table_id = aws_route_table.private[each.key].id
}

Three details worth stopping on. First, the for_each keys are the AZ names, not list positions, so adding a zone does not renumber the others, the key-stability point from earlier. Second, the NAT gateway page in the provider docs recommends an explicit depends_on on the internet gateway, which I copied. Third, a subnet is “public” because its route table sends 0.0.0.0/0 to an internet gateway, not because of a flag on the subnet. The private route tables point at a NAT gateway instead.

What it costs

The tidy design, one NAT gateway per zone, is the expensive one. NAT gateways bill by the hour and by the data processed, and one per zone triples the hourly part. Many non-production environments use a single NAT gateway and accept that a zone outage takes down egress for the others. That is a design trade, not a mistake, and it should be a variable:

variable "single_nat_gateway" { type = bool }

I pulled the public AWS Price List file for the VPC service in eu-west-1, published 25 November 2026. It does not include NAT gateways, which sit in the EC2 price file, so I do not quote a NAT price. What it does list: $0.005 per hour for each in-use public IPv4 address, $0.011 per hour for each interface VPC endpoint, and $0.01 per GB processed by those endpoints. Over a 730-hour month those are $3.65 per public IPv4 address and $8.03 per interface endpoint, and one endpoint per zone per service adds up. Public IPv4 addresses are no longer free, so putting every instance in a public subnet with its own address costs money too. A VPC endpoint can still pay for itself by keeping traffic to an AWS service off the NAT gateway.

Or use a module

You do not have to write all this. In the registry the terraform-aws-modules/vpc/aws module is at 6.9.0 as of 25 November 2026, and declares 79 resource blocks and 239 input variables. It covers everything above plus flow logs, IPv6, extra route tables and more. The trade is the same as in the modules lessons: a big shared module saves writing and costs reading. Write the raw version once so you understand the resources, then decide.

Put the network in its own state. It changes rarely and everything depends on it, which is the pattern that lesson describes.

About the video

The embed is Anton Putra’s “Terraform AWS VPC Tutorial - Public, Private, and Isolated Subnets”, 23 minutes 26 seconds, May 2025. The description I saw listed it as part of his Terraform tutorial playlist and does not otherwise describe the contents, so I take its scope from the title: public, private and isolated subnets. It is recent, so it should reflect current provider behaviour, but I did not watch it to check. English was judged from the title, description, channel and its English auto-caption track. It builds on AWS, so the resource names above apply, and the cost caveats are mine, not the video’s.

Where this fits

A network is empty until something runs in it, and something needs permission to do anything. IAM roles and policies comes next.

Check yourself

  1. 01What does cidrsubnet("10.0.0.0/16", 8, 3) return?

    10.0.3.0/24: it adds 8 bits to the /16 prefix and selects block number 3, counting from zero.

  2. 02Why key aws_subnet resources by AZ name?

    Keys are stable when a zone is added, whereas list positions would shift and plan replacements.

  3. 03What makes a subnet public?

    Its route table has a 0.0.0.0/0 route to an internet gateway. There is no public flag on the subnet itself.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark