A VPC & Subnets Across Zones
Amazon VPC and Subnets explained the design: one VPC per environment, a CIDR block big enough to grow, and in every availability zone a public subnet (load balancers, NAT gateways) and a private subnet (applications, databases). Here is that design as code, computed from three inputs instead of a hand-written table of CIDRs.
The code
variable "name" {
type = string # linkly-prod
}
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 {
# zone => index, e.g. { "eu-west-1a" = 0, ... }
az_index = { for i, az in var.azs : az => i }
}
resource "aws_vpc" "this" {
cidr_block = var.cidr
enable_dns_support = true
enable_dns_hostnames = true # needed for RDS endpoints, EKS, interface endpoints
tags = { Name = var.name }
}
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) # 10.20.0.0/24, .1, .2
map_public_ip_on_launch = true
tags = { Name = "${var.name}-public-${each.key}", Tier = "public" }
}
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) # 10.20.16.0/20, 32, 48
tags = { Name = "${var.name}-private-${each.key}", Tier = "private" }
}
output "vpc_id" {
value = aws_vpc.this.id
}
output "public_subnet_ids" {
value = [for az in var.azs : aws_subnet.public[az].id]
}
output "private_subnet_ids" {
value = [for az in var.azs : aws_subnet.private[az].id]
}Design notes:
- Subnets keyed by zone with
for_each, so adding a fourth zone later adds two subnets and touches nothing else (see for_each & Stable Keys). - Private subnets are bigger (
/20, 4,091 usable addresses each) than public ones (/24): pods in EKS take one VPC IP each, and running out of addresses is a real outage. Public subnets only hold load balancers and NAT gateways. - The CIDR maths keeps the two ranges apart: public subnets use the first
/20(10.20.0.0–10.20.15.255), private subnets the next three. - Outputs are lists in zone order, because the consumers (RDS subnet groups, EKS, load balancers) take lists.
- Zone names are a variable here so the code stays offline; in real use, take them from
data "aws_availability_zones"(withslice(…, 0, 3)) or set them per environment.
Planning it offline
The session writes the code above (shortened with a heredoc per file), plans it with the teaching provider setup and prints the planned subnets from the plan's JSON:
mkdir vpc && cd vpc
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 > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
variable "name" {
type = string
default = "linkly-prod"
}
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
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = var.name }
}
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)
map_public_ip_on_launch = true
tags = { Name = "${var.name}-public-${each.key}", Tier = "public" }
}
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)
tags = { Name = "${var.name}-private-${each.key}", Tier = "private" }
}
HCL
tofu init >/dev/null
tofu validate
tofu plan -out=tfplan | grep '^Plan:'
tofu show -json tfplan | jq -r '.resource_changes[] | select(.type == "aws_subnet") | [.address, .change.after.availability_zone, .change.after.cidr_block] | @tsv'Success! The configuration is valid.
Plan: 7 to add, 0 to change, 0 to destroy.
aws_subnet.private["eu-west-1a"] eu-west-1a 10.20.16.0/20
aws_subnet.private["eu-west-1b"] eu-west-1b 10.20.32.0/20
aws_subnet.private["eu-west-1c"] eu-west-1c 10.20.48.0/20
aws_subnet.public["eu-west-1a"] eu-west-1a 10.20.0.0/24
aws_subnet.public["eu-west-1b"] eu-west-1b 10.20.1.0/24
aws_subnet.public["eu-west-1c"] eu-west-1c 10.20.2.0/24
Testing the maths
The CIDR layout is exactly the kind of logic worth a test: a mistake there is expensive to fix later (subnets can't be resized). This test, with a mocked provider, checks that no two subnets overlap, for three zones and for four:
mkdir -p vpc/tests && cd vpc
cat > main.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"]
}
variable "public_newbits" {
type = number
default = 8 # /24 public subnets in a /16
}
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, var.public_newbits, 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)
}
locals {
all_cidrs = concat([for s in aws_subnet.public : s.cidr_block], [for s in aws_subnet.private : s.cidr_block])
# two blocks overlap when they share a network address at the shorter of their two prefix lengths
prefix = [for c in local.all_cidrs : tonumber(split("/", c)[1])]
overlapping = flatten([
for i, a in local.all_cidrs : [
for j, b in local.all_cidrs : "${a} and ${b}"
if i < j && cidrhost("${split("/", a)[0]}/${min(local.prefix[i], local.prefix[j])}", 0) == cidrhost("${split("/", b)[0]}/${min(local.prefix[i], local.prefix[j])}", 0)
]
])
}
output "all_cidrs" {
value = local.all_cidrs
}
output "overlapping" {
value = local.overlapping
}
HCL
cat > tests/layout.tftest.hcl <<'HCL'
mock_provider "aws" {}
run "three_zones_do_not_overlap" {
command = plan
assert {
condition = length(output.overlapping) == 0
error_message = "overlapping subnets: ${jsonencode(output.overlapping)}"
}
assert {
condition = length(output.all_cidrs) == 6
error_message = "expected 3 public + 3 private subnets"
}
}
run "a_wrong_layout_is_caught" {
command = plan
variables {
public_newbits = 4 # /20 public subnets: the second one is the first private subnet
}
assert {
condition = length(output.overlapping) > 0
error_message = "the overlap check should catch this"
}
}
run "four_zones" {
command = plan
variables {
azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c", "eu-west-1d"]
}
assert {
condition = length(output.all_cidrs) == 8 && length(output.overlapping) == 0
error_message = "expected 8 subnets without overlaps"
}
}
HCL
tofu init >/dev/null
tofu testtests/layout.tftest.hcl... pass
run "three_zones_do_not_overlap"... pass
run "a_wrong_layout_is_caught"... pass
run "four_zones"... pass
Success! 3 passed, 0 failed.
The overlap rule compares every pair of blocks (by position, so two identical blocks count too) at the shorter of their prefix lengths, and the second run proves the check can fail: this copy of the module makes the public subnets' size a variable, and with /20 public subnets the second one, 10.20.16.0/20, is exactly the first private subnet. What matters is that the layout is tested once, in code, rather than re-checked by eye in every review.
What a real apply looks like
$ tofu apply
…
aws_vpc.this: Creating...
aws_vpc.this: Creation complete after 2s [id=vpc-0c1f2e3d4a5b69788]
aws_subnet.private["eu-west-1b"]: Creating...
aws_subnet.public["eu-west-1a"]: Creating...
…
aws_subnet.public["eu-west-1a"]: Creation complete after 11s [id=subnet-0a1b2c3d4e5f60718]
…
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.The subnets exist, but nothing can reach the internet yet: that needs an internet gateway, NAT and route tables, next lesson.
Test yourself
Why are the subnets created with for_each keyed by availability zone instead of count?
- count can't create subnets
- Adding or removing a zone then only touches that zone's subnets
- for_each is faster
- AWS requires it
What is cidrsubnet("10.20.0.0/16", 4, 2)?
- 10.20.2.0/20
- 10.20.32.0/20
- 10.20.0.2/16
- 10.20.2.0/24
Why make private subnets larger than public ones?
- Public subnets are more expensive
- Workloads (EKS pods, instances, databases) consume private IPs; public subnets mostly hold load balancers and NAT gateways
- AWS limits public subnets to /24
- Private subnets need broadcast addresses