Skip to main content

Infrastructure as code · Intermediate · 20 min

Build the Relay network with OpenTofu: VPC, subnets, routes and security groups

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74

You will add a VPC, public and private subnets in two availability zones, an internet route and a web security group to the Relay project, then apply them and list the subnet IDs per zone.

On this page

In part 1 you laid out the Relay project and created its assets bucket. Relay's web server, which arrives in part 3, needs somewhere to live: a network of its own, with a way in from the internet and rules about who may connect. In this part you write that network as code.

By the end, ~/relay-demo has two new files, network.tf and security.tf, plus a few new variables and outputs. Together they describe:

  • a VPC with a /16 address range
  • one public and one private subnet in each of two availability zones, with addresses worked out by cidrsubnet() rather than typed by hand
  • an internet gateway and a public route table, and a private route table with no way out
  • a security group that lets anyone reach ports 80 and 443, and only your address reach port 22

There is no NAT gateway, on purpose. You will see why, and what it would cost, in step 4.

Nothing in this part bills on its own: AWS does not charge for a VPC, subnets, route tables, an internet gateway or security groups. Charges start in part 3, when an instance and its public address appear.

Step 1 · Add the network variables

Two values change between environments and between readers: the VPC's address range, and the address allowed to use SSH. Make both variables, with validation so a mistake fails at plan time rather than after AWS has built something.

Go to the project and append the two variables to variables.tf. The >> adds to the end of the file and leaves part 1's variables as they are:

Bash
cd ~/relay-demo
cat >> variables.tf <<'HCL'

variable "vpc_cidr" {
  type        = string
  description = "Address range for the Relay VPC. Must be a /16."
  default     = "10.20.0.0/16"

  validation {
    condition     = can(cidrhost(var.vpc_cidr, 0)) && endswith(var.vpc_cidr, "/16")
    error_message = "vpc_cidr must be a valid IPv4 range ending in /16, such as 10.20.0.0/16."
  }
}

variable "ssh_allowed_cidr" {
  type        = string
  description = "The one IPv4 range allowed to connect on port 22, usually your own address as a /32."

  validation {
    condition     = can(cidrnetmask(var.ssh_allowed_cidr)) && var.ssh_allowed_cidr != "0.0.0.0/0"
    error_message = "ssh_allowed_cidr must be an IPv4 range such as 198.51.100.7/32, and never 0.0.0.0/0."
  }
}
HCL

ssh_allowed_cidr has no default, so every plan has to say who may connect. Put your value in dev.tfvars. The address below comes from a range reserved for documentation, so it matches nobody: replace 203.0.113.10 with your own public IPv4 address, which you can see by running curl -4 https://checkip.amazonaws.com on the machine you will connect from.

Bash
cat >> dev.tfvars <<'HCL'
ssh_allowed_cidr = "203.0.113.10/32" # replace this with your own address
HCL

Part 1 also left a prod.tfvars. Because the variable has no default, a prod plan would now stop and ask for it, so add the same line there (production often uses a different address, such as an office or VPN range):

Bash
cat >> prod.tfvars <<'HCL'
ssh_allowed_cidr = "203.0.113.10/32" # replace this with your own address
HCL

If you connect over a mobile network or a prepaid data bundle, your public address may change each time you reconnect, which is common on many networks across Africa and elsewhere. When SSH suddenly stops working, check the address again, update dev.tfvars and apply. Changing one rule is quick and leaves everything else alone.

Check it worked

cat dev.tfvars shows part 1's values (environment = "dev", region, force_destroy_assets and extra_tags) and, at the end, the new ssh_allowed_cidr line, and tail -n 1 prod.tfvars shows the same line. grep -c '^variable' variables.tf counts two more variables than before.

Step 2 · Work out the subnets with cidrsubnet and a map

Each subnet needs an availability zone and a slice of the VPC's range. Rather than hard-code zone names, which differ between Regions and accounts, ask AWS which zones are available and take the first two. Rather than type four address ranges, describe the layout once and let cidrsubnet() compute them.

Create network.tf with the lookup and the layout:

Bash
cat > network.tf <<'HCL'
data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  # The first two zones, sorted so the choice is the same on every run.
  zones = slice(sort(data.aws_availability_zones.available.names), 0, 2)

  # One entry per subnet. The key is stable even if AWS adds zones.
  # zone is an index into local.zones; netnum picks the /24 inside the /16.
  subnet_layout = {
    "public-a"  = { tier = "public", zone = 0, netnum = 0 }
    "public-b"  = { tier = "public", zone = 1, netnum = 1 }
    "private-a" = { tier = "private", zone = 0, netnum = 10 }
    "private-b" = { tier = "private", zone = 1, netnum = 11 }
  }
}
HCL

cidrsubnet(prefix, newbits, netnum) cuts a range into smaller ones. With the default 10.20.0.0/16, adding 8 bits gives /24 subnets of 256 addresses each, and netnum says which one: 0 is 10.20.0.0/24, 1 is 10.20.1.0/24, 10 is 10.20.10.0/24 and 11 is 10.20.11.0/24. Leaving 2 to 9 free keeps room for more public subnets later without renumbering the private ones. AWS keeps five addresses in every subnet for itself, so each /24 gives you 251.

The map keys, such as public-a, matter more than they look. for_each uses them as the address of each subnet in the state, so aws_subnet.this["public-a"] stays the same resource for as long as the key does. If you had used count over a list, removing the first item would shift every index and OpenTofu would plan to replace subnets that had not changed.

You can check the arithmetic before writing any resource. tofu console evaluates expressions against your configuration:

Bash
echo 'cidrsubnet(var.vpc_cidr, 8, 11)' | tofu console -var-file=dev.tfvars
echo '[for key, s in local.subnet_layout : cidrsubnet(var.vpc_cidr, 8, s.netnum)]' | tofu console -var-file=dev.tfvars

Check it worked

The first command prints "10.20.11.0/24". The second prints all four ranges in key order (private-a, private-b, public-a, public-b): 10.20.10.0/24, 10.20.11.0/24, 10.20.0.0/24 and 10.20.1.0/24. The zone names come from AWS during the plan, so you see them in step 6.

Step 3 · Write the VPC, subnets and routes

Append the resources to network.tf:

Bash
cat >> network.tf <<'HCL'

resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "${local.name_prefix}-vpc"
  }
}

resource "aws_subnet" "this" {
  for_each = local.subnet_layout

  vpc_id                  = aws_vpc.main.id
  availability_zone       = local.zones[each.value.zone]
  cidr_block              = cidrsubnet(var.vpc_cidr, 8, each.value.netnum)
  map_public_ip_on_launch = each.value.tier == "public"

  tags = {
    Name = "${local.name_prefix}-${each.key}"
    Tier = each.value.tier
  }
}

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

  tags = {
    Name = "${local.name_prefix}-igw"
  }
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "${local.name_prefix}-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" "private" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "${local.name_prefix}-private"
  }
}

resource "aws_route_table_association" "this" {
  for_each = aws_subnet.this

  subnet_id      = each.value.id
  route_table_id = local.subnet_layout[each.key].tier == "public" ? aws_route_table.public.id : aws_route_table.private.id
}
HCL

What makes a subnet "public" is not a setting on the subnet. It is the route table it is associated with. Both public subnets use the table whose 0.0.0.0/0 route points at the internet gateway, so traffic for any address outside the VPC leaves through it. The private table has only the local route AWS adds to every table, so instances there can talk to the rest of the VPC and nothing else.

map_public_ip_on_launch gives instances in the public subnets a public IPv4 address automatically. That address is what part 3's web server is reached on, and it is also what bills, so it is switched on only where it is needed.

The association uses for_each = aws_subnet.this, so it gets the same four keys as the subnets, and it picks a table from the subnet's tier. The route is a separate aws_route resource rather than a block inside the table, which keeps a later route (to a peered VPC, say) as one more resource instead of an edit to this one.

Check it worked

grep -c '^resource' network.tf prints 7: the VPC, the subnets, the gateway, two route tables, the route and the associations. for_each turns the subnets and associations into four instances each when you plan.

Step 4 · Decide about NAT, and leave it out

Instances in the private subnets cannot reach the internet, not even to install updates. The usual fix is a NAT gateway in each public subnet with a route to it from the private table. Relay does not add one, for three reasons:

  • It bills by the hour, used or not. On the AWS VPC pricing page, checked on 26 November 2026, a NAT gateway in US East (Ohio) costs $0.045 per hour plus $0.045 per GB it processes. One gateway running all month is about 730 hours, so roughly $33 before any data, and a gateway in each of two zones doubles that. Prices differ by Region; read the page for yours.
  • Relay does not need it yet. The only instance, in part 3, sits in a public subnet with its own address.
  • It is easy to add later. The private subnets and their route table are already here. Adding NAT is one aws_nat_gateway, one Elastic IP and one aws_route in the private table.

The private subnets are kept for what comes later, such as a database that should never have a public address. Leaving them empty costs nothing.

If many of your users are in Africa, a Region on the continent such as af-south-1 (Cape Town) can cut latency. It is an opt-in Region: you enable it in the account first, then set region in your tfvars. Check that Region's prices too, since they are not the same everywhere.

Check it worked

grep -c nat_gateway network.tf prints 0. You should be able to say in one sentence why a private instance here cannot run apt update: its route table has no route out of the VPC.

Step 5 · Write the web security group

A security group is a firewall attached to an instance's network interface. It allows traffic that matches a rule and drops everything else. Create security.tf:

Bash
cat > security.tf <<'HCL'
resource "aws_security_group" "web" {
  name        = "${local.name_prefix}-web"
  description = "Relay web server: HTTP and HTTPS from anywhere, SSH from one range"
  vpc_id      = aws_vpc.main.id

  tags = {
    Name = "${local.name_prefix}-web"
  }
}

resource "aws_vpc_security_group_ingress_rule" "http" {
  security_group_id = aws_security_group.web.id
  description       = "HTTP from anywhere"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 80
  to_port           = 80
}

resource "aws_vpc_security_group_ingress_rule" "https" {
  security_group_id = aws_security_group.web.id
  description       = "HTTPS from anywhere"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "tcp"
  from_port         = 443
  to_port           = 443
}

resource "aws_vpc_security_group_ingress_rule" "ssh" {
  security_group_id = aws_security_group.web.id
  description       = "SSH from the operator only"
  cidr_ipv4         = var.ssh_allowed_cidr
  ip_protocol       = "tcp"
  from_port         = 22
  to_port           = 22
}

resource "aws_vpc_security_group_egress_rule" "all" {
  security_group_id = aws_security_group.web.id
  description       = "All outbound traffic"
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
}
HCL

Each rule is its own resource instead of an ingress block inside the group. The AWS provider documentation recommends this form: each rule gets its own ID and tags, and changing the SSH address changes one rule resource rather than the whole group. Do not mix the two styles on one group, because each would keep removing the other's rules.

The egress rule matters. AWS adds an allow-all outbound rule to every new group, but the provider removes it when it creates aws_security_group, so a group with no egress rule in code allows nothing out. Part 3's server needs outbound access to download Nginx, so the rule is written down here where you can see it. ip_protocol = "-1" means every protocol, and it takes no ports.

These rules cover IPv4 only. The VPC has no IPv6 range, so there is nothing to allow over IPv6 yet.

Check it worked

grep -c 'aws_vpc_security_group_ingress_rule' security.tf prints 3. The only rule that names something other than 0.0.0.0/0 is ssh, and it reads the variable.

Step 6 · Format, validate and plan

Tidy the files to the standard style, check them, and save a plan:

Bash
tofu fmt
tofu validate
tofu plan -var-file=dev.tfvars -out=network.tfplan

tofu fmt rewrites files to the standard layout and prints the name of each one it changed, or nothing. tofu validate should print Success! The configuration is valid. No tofu init is needed this time: the new resources come from the AWS provider part 1 already installed.

Before you apply, try the guard on the SSH variable. This plan should fail:

Bash
tofu plan -var-file=dev.tfvars -var 'ssh_allowed_cidr=0.0.0.0/0'

Check it worked

The saved plan ends with Plan: 18 to add, 0 to change, 0 to destroy. That is 1 VPC, 4 subnets, 1 internet gateway, 2 route tables, 1 route, 4 associations, 1 security group, 3 ingress rules and 1 egress rule. The assets bucket from part 1 does not appear, because it has not changed. Each subnet shows its cidr_block already worked out, such as 10.20.10.0/24 for aws_subnet.this["private-a"], and its availability_zone, such as eu-west-1a. The 0.0.0.0/0 plan stops with an invalid-value error for ssh_allowed_cidr that shows your error message, and creates nothing.

Step 7 · Apply, then prove the plan is empty

Apply the plan you just read:

Bash
tofu apply network.tfplan

Then plan again with nothing changed. -detailed-exitcode makes the result machine-readable: exit code 0 means no changes, 2 means there are changes, and 1 means an error.

Bash
tofu plan -var-file=dev.tfvars -detailed-exitcode

A second plan that is not empty means something in your code disagrees with what AWS stores, for example a value AWS normalises differently. Fix it now, while the configuration is small. Part 8 of this series turns the same exit code into a nightly drift check.

Check it worked

The apply ends with Apply complete! Resources: 18 added, 0 changed, 0 destroyed. The second plan prints No changes. Your infrastructure matches the configuration., and echo $? straight after it prints 0.

Step 8 · Output the subnet IDs per zone

Part 3 needs a public subnet and the security group, and a later part will need the private subnets. Append outputs that group subnet IDs by zone:

Bash
cat >> outputs.tf <<'HCL'

output "vpc_id" {
  description = "ID of the Relay VPC."
  value       = aws_vpc.main.id
}

output "public_subnet_ids" {
  description = "Public subnet ID per availability zone."
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "public" }
}

output "private_subnet_ids" {
  description = "Private subnet ID per availability zone."
  value       = { for key, subnet in aws_subnet.this : subnet.availability_zone => subnet.id if local.subnet_layout[key].tier == "private" }
}

output "web_security_group_id" {
  description = "ID of the web security group."
  value       = aws_security_group.web.id
}
HCL
tofu fmt
tofu apply -var-file=dev.tfvars -auto-approve
tofu output public_subnet_ids
tofu output private_subnet_ids

Adding outputs changes no resources, so the apply reports 0 added, 0 changed, 0 destroyed and only saves the new outputs to the state. -auto-approve is safe here for that reason; when a plan touches resources, save it and read it first as you did above.

Check it worked

Each tofu output prints a map with two entries, one per zone, such as:

Text
{
  "eu-west-1a" = "subnet-0a1b2c3d4e5f60718"
  "eu-west-1b" = "subnet-0f1e2d3c4b5a69788"
}

Your zone names and IDs differ. In the AWS console, under VPC and then Subnets, filtering by the tag Project = relay shows the same four subnets, two marked Tier = public. Leave everything in place: part 3 launches the web server into this network.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.