Lab: a two-tier network with public and private subnets
Build a VPC across two availability zones with OpenTofu: public and private subnets, an internet gateway, a NAT gateway, route tables, chained security groups and a private test instance. Then prove the routes, the rules and the egress path with real commands, and tear it all down with one command.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Provider, variables and default tags
- Step 2: Subnets, gateways and route tables
- Step 3: Security groups that reference each other
- Step 4: A private probe instance and the outputs
- Step 5: Validate, plan and apply
- Step 6: Check the routes and rules that AWS actually holds
- Step 7: Test the egress path from inside, including what must fail
- Step 8: Tear down with one command
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Cloud Basics
- What you rent, what you still own, and which service to pick Concept · 25 min
- Lab: a two-tier network with public and private subnets Lab · 30 min
- Identities, roles and least-privilege policies Worked example · 20 min
- Cost as an engineering signal: tags, budgets, rightsizing and teardown Worked example · 20 min
- Lab: automated backups and a timed restore Lab · 25 min
- Check: architecture, permissions and recovery review Knowledge check · 10 questions
What you will learn
- Design a virtual network with public and private subnets, route tables, an egress path and security groups that expose only what is needed.
Prerequisites: Networking Basics
01. Goal and setup
You will build the network that a small web service with a database needs, then check it from the outside and from the inside. By the end you will have:
- a VPC (virtual private cloud: your own private network in a region) with the range
10.0.0.0/16; - a public and a private subnet in each of two availability zones (AZs), because a load balancer and a database subnet group each need subnets in at least two AZs;
- an internet gateway, a NAT gateway for outbound traffic from private hosts, and a route table per tier;
- three security groups (ALB, app, database) whose rules reference each other instead of IP ranges;
- a probe instance in a private subnet, reached through Session Manager, to test the egress path without opening any inbound port.
Lab 7 adds the database to this folder; the skill practice adds the load balancer.
Resource contract. As agreed in lesson 1: a sandbox AWS account, one region (the variable defaults to ap-southeast-1), a budget alert in place, and everything tagged Project=cloud-basics-lab. The NAT gateway and its public IPv4 address bill by the hour, so run tofu destroy the same day unless you go straight on to lab 7.
You need: OpenTofu 1.10 or later (or Terraform 1.10 or later: replace tofu with terraform), AWS CLI v2, and short-lived credentials for the sandbox account, not a long-lived access key. The files target the hashicorp/aws provider 6.24 or later (6.24 added the availability_mode argument this lab uses).
cloud-lab/
├── providers.tf step 1: provider, version pins and default tags
├── variables.tf step 1: region, owner and expiry
├── terraform.tfvars step 1: your values
├── network.tf step 2: VPC, subnets, gateways and route tables
├── security.tf step 3: security groups and their rules
├── probe.tf step 4: a private test instance with an SSM role
└── outputs.tf step 4: IDs the checks in steps 6 and 7 usemkdir cloud-lab && cd cloud-lab
tofu version
aws --version
aws sts get-caller-identity # must show the sandbox accountOpenTofu v1.13.9
on linux_amd64
aws-cli/2.x.y Python/3.x.y Linux/6.x exe/x86_64
{
"UserId": "AROAEXAMPLEROLEID:[email protected]",
"Account": "123456789012",
"Arn": "arn:aws:sts::123456789012:assumed-role/SandboxAdmin/[email protected]"
}02. Step 1: Provider, variables and default tags
default_tags stamps the same four tags on every resource the provider creates. That is what makes the cost and teardown checks later in this skill work: you can find, and bill, everything the lab made by asking for Project=cloud-basics-lab.
terraform {
required_version = ">= 1.10"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.24"
}
}
}
provider "aws" {
region = var.region
default_tags {
tags = {
Project = "cloud-basics-lab"
Environment = "ephemeral"
Owner = var.owner
ExpiresAt = var.expires_at
}
}
}variable "region" {
type = string
description = "The one region every lab in this skill uses"
default = "ap-southeast-1"
}
variable "owner" {
type = string
description = "Who to ask about these resources (a handle or email)"
}
variable "expires_at" {
type = string
description = "UTC time by which everything must be destroyed"
}owner = "your-handle"
# UTC; set it a few hours after the time you start the lab
expires_at = "2026-11-26T18:00:00Z"tofu initInitializing provider plugins...
- Finding hashicorp/aws versions matching "~> 6.24"...
- Installing hashicorp/aws v6.73.0...
- Installed hashicorp/aws v6.73.0 (signed, key ID 0C0AF313E5FD9F80)
...
OpenTofu has been successfully initialized!03. Step 2: Subnets, gateways and route tables
A subnet is not public or private because of its addresses: every subnet here uses private RFC 1918 ranges. A public subnet's route table sends 0.0.0.0/0 (everything outside the VPC) to the internet gateway, so its hosts can reach the internet if they also have a public IP. A private subnet has no route to the internet gateway, so nothing on the internet can open a connection to its hosts. Its default route goes to the NAT gateway, which lets those hosts start outbound connections and carries the replies back. This lab uses a zonal NAT gateway, the provider's default mode: it lives in one subnet of one AZ, so it must sit in a public subnet, whose route leads to the internet gateway, and it uses an Elastic IP. Keep public subnets for internet-facing entry points: load balancers, zonal NAT gateways and, if you cannot avoid one, a bastion host.
One trade-off is deliberate. To save money there is a single zonal NAT gateway, in the first AZ: if that AZ fails, private hosts in the second AZ lose egress too. Production designs avoid that in one of two ways:
- a regional NAT gateway (
availability_mode = "regional"), which AWS now recommends for most public NAT use. It needs no public subnet, spreads itself across the AZs where your workloads run (expanding into a new AZ can take up to an hour, during which traffic crosses zones), and every private route table can point at its one ID. It does not support private NAT; - one zonal NAT gateway per AZ, each in its own public subnet, with a private route table per AZ that points at its own zone's gateway.
The lab keeps the zonal mode because it makes every piece visible (the public subnet, the Elastic IP and the route you check in step 6) and gives one address to test in step 7. The AZ names come from a data source, so the file works in any region with two AZs.
data "aws_availability_zones" "available" {
state = "available"
}
locals {
azs = slice(data.aws_availability_zones.available.names, 0, 2)
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags = { Name = "lab-vpc" }
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = { Name = "lab-igw" }
}
# 10.0.1.0/24 and 10.0.2.0/24: one public subnet per AZ
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index + 1}.0/24"
availability_zone = local.azs[count.index]
tags = { Name = "lab-public-${count.index}", Tier = "public" }
}
# 10.0.11.0/24 and 10.0.12.0/24: one private subnet per AZ
resource "aws_subnet" "private" {
count = 2
vpc_id = aws_vpc.main.id
cidr_block = "10.0.${count.index + 11}.0/24"
availability_zone = local.azs[count.index]
map_public_ip_on_launch = false # the default, stated for clarity
tags = { Name = "lab-private-${count.index}", Tier = "private" }
}
resource "aws_eip" "nat" {
domain = "vpc"
tags = { Name = "lab-nat-eip" }
}
# Zonal mode (the default): one AZ, placed in a public subnet.
resource "aws_nat_gateway" "main" {
availability_mode = "zonal"
allocation_id = aws_eip.nat.id
subnet_id = aws_subnet.public[0].id
tags = { Name = "lab-nat" }
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
}
tags = { Name = "lab-public-rt" }
}
resource "aws_route_table" "private" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.main.id
}
tags = { Name = "lab-private-rt" }
}
resource "aws_route_table_association" "public" {
count = 2
subnet_id = aws_subnet.public[count.index].id
route_table_id = aws_route_table.public.id
}
resource "aws_route_table_association" "private" {
count = 2
subnet_id = aws_subnet.private[count.index].id
route_table_id = aws_route_table.private.id
}Every subnet gets an explicit association. A subnet without one silently uses the VPC's main route table, which here holds only the local route for 10.0.0.0/16. That is safe but confusing: a "public" subnet you forgot to associate would have no internet path at all.
04. Step 3: Security groups that reference each other
Routes decide where packets can go; security groups decide which connections are allowed, per network interface. They are stateful: replies to an allowed connection are allowed automatically. Network ACLs, the stateless filter on a whole subnet, stay at their allow-all default here.
The chain admits traffic by role, not by address:
- ALB group: 443 in from anywhere; out only to the app group on 8080.
- App group: 8080 in only from the ALB group; out to the database group on 5432 and to anywhere on 443 (through the NAT gateway, for updates and AWS APIs).
- Database group: 5432 in only from the app group; no outbound rules.
A rule that names a security group admits any interface that carries that group, wherever its address is. A rule naming the app subnet's CIDR would admit every host in that subnet.
OpenTofu differs from the console here. AWS adds an allow-all egress rule to a new group, but the aws_security_group resource removes it, so every outbound path below exists only because a rule declares it. The separate rule resources are what the provider documentation recommends, and they avoid a dependency cycle between the ALB and app groups.
resource "aws_security_group" "alb" {
name = "lab-alb"
description = "Internet-facing load balancer"
vpc_id = aws_vpc.main.id
}
resource "aws_security_group" "app" {
name = "lab-app"
description = "Application tier in the private subnets"
vpc_id = aws_vpc.main.id
}
resource "aws_security_group" "db" {
name = "lab-db"
description = "PostgreSQL, reachable only from the app tier"
vpc_id = aws_vpc.main.id
}
resource "aws_vpc_security_group_ingress_rule" "alb_https" {
security_group_id = aws_security_group.alb.id
description = "HTTPS from the internet"
ip_protocol = "tcp"
from_port = 443
to_port = 443
cidr_ipv4 = "0.0.0.0/0"
}
resource "aws_vpc_security_group_egress_rule" "alb_to_app" {
security_group_id = aws_security_group.alb.id
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
referenced_security_group_id = aws_security_group.app.id
}
resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
security_group_id = aws_security_group.app.id
ip_protocol = "tcp"
from_port = 8080
to_port = 8080
referenced_security_group_id = aws_security_group.alb.id
}
resource "aws_vpc_security_group_egress_rule" "app_to_db" {
security_group_id = aws_security_group.app.id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
referenced_security_group_id = aws_security_group.db.id
}
resource "aws_vpc_security_group_egress_rule" "app_https_out" {
security_group_id = aws_security_group.app.id
description = "HTTPS out through the NAT gateway"
ip_protocol = "tcp"
from_port = 443
to_port = 443
cidr_ipv4 = "0.0.0.0/0"
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
security_group_id = aws_security_group.db.id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
referenced_security_group_id = aws_security_group.app.id
}05. Step 4: A private probe instance and the outputs
To test from the inside without opening SSH, the probe gets an instance role with the AWS managed policy AmazonSSMManagedInstanceCore. The Systems Manager agent on Amazon Linux 2023 uses it to register over outbound HTTPS, and you open a shell through Session Manager: no inbound rule, key pair or public IP. Lesson 4 explains roles. The image ID comes from the public SSM parameter for the latest Amazon Linux 2023 image in your region (insecure_value only means the provider shows it in plans; an image ID is not secret). The probe carries the app group, so it has exactly the paths an app server would have.
data "aws_ssm_parameter" "al2023" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64"
}
data "aws_iam_policy_document" "ec2_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "probe" {
name = "lab-probe"
assume_role_policy = data.aws_iam_policy_document.ec2_assume.json
}
resource "aws_iam_role_policy_attachment" "probe_ssm" {
role = aws_iam_role.probe.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "probe" {
name = "lab-probe"
role = aws_iam_role.probe.name
}
resource "aws_instance" "probe" {
ami = data.aws_ssm_parameter.al2023.insecure_value
instance_type = "t4g.micro"
subnet_id = aws_subnet.private[0].id
vpc_security_group_ids = [aws_security_group.app.id]
iam_instance_profile = aws_iam_instance_profile.probe.name
metadata_options {
http_tokens = "required" # IMDSv2 only
}
tags = { Name = "lab-probe" }
lifecycle {
ignore_changes = [ami] # a newer image must not replace the probe
}
# Boot only once the private route to the NAT gateway exists.
depends_on = [aws_route_table_association.private]
}output "vpc_id" { value = aws_vpc.main.id }
output "public_subnet_ids" { value = aws_subnet.public[*].id }
output "private_subnet_ids" { value = aws_subnet.private[*].id }
output "nat_public_ip" { value = aws_eip.nat.public_ip }
output "probe_instance_id" { value = aws_instance.probe.id }
output "alb_sg_id" { value = aws_security_group.alb.id }
output "app_sg_id" { value = aws_security_group.app.id }
output "db_sg_id" { value = aws_security_group.db.id }06. Step 5: Validate, plan and apply
Read the plan before you apply it. You should see 27 resources: the VPC, the internet gateway, four subnets, the Elastic IP, the NAT gateway, two route tables, four associations, three security groups, six rules, three IAM resources and the instance. Saving the plan to a file and applying that file makes OpenTofu perform exactly the actions you reviewed; if the state has changed since you saved it, OpenTofu refuses the file and you plan again. The NAT gateway takes a few minutes to become available.
tofu fmt -check && tofu validate
tofu plan -out lab.tfplan
tofu apply lab.tfplanSuccess! The configuration is valid.
...
Plan: 27 to add, 0 to change, 0 to destroy.
...
Apply complete! Resources: 27 added, 0 changed, 0 destroyed.
Outputs:
alb_sg_id = "sg-01111111111111111"
app_sg_id = "sg-02222222222222222"
db_sg_id = "sg-03333333333333333"
nat_public_ip = "203.0.113.10"
private_subnet_ids = [
"subnet-0cccccccccccccccc",
"subnet-0dddddddddddddddd",
]
probe_instance_id = "i-06666666666666666"
public_subnet_ids = [
"subnet-0aaaaaaaaaaaaaaaa",
"subnet-0bbbbbbbbbbbbbbbb",
]
vpc_id = "vpc-07777777777777777"07. Step 6: Check the routes and rules that AWS actually holds
A successful apply proves only that the API accepted your requests. Ask AWS what it now holds. The first query prints, for each route table, its name, how many subnets use it and where its default route goes (internet gateway or NAT gateway). The second lists every rule on the database group.
VPC=$(tofu output -raw vpc_id)
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$VPC" \
--query 'RouteTables[].[Tags[?Key==`Name`]|[0].Value,
length(Associations[?SubnetId]),
Routes[?DestinationCidrBlock==`0.0.0.0/0`]|[0].GatewayId,
Routes[?DestinationCidrBlock==`0.0.0.0/0`]|[0].NatGatewayId]' \
--output text
aws ec2 describe-security-group-rules \
--filters "Name=group-id,Values=$(tofu output -raw db_sg_id)" \
--query 'SecurityGroupRules[].[IsEgress,IpProtocol,FromPort,ToPort,
CidrIpv4,ReferencedGroupInfo.GroupId]' --output textlab-public-rt 2 igw-04444444444444444 None
lab-private-rt 2 None nat-05555555555555555
None 0 None None
False tcp 5432 5432 None sg-02222222222222222Read the result against the design:
- The public table serves two subnets and sends the default route to
igw-…; the private table serves two and sends it tonat-…. - The unnamed row is the VPC's main route table, with no subnets. A subnet listed there has lost its association.
- The database group has one rule: ingress (
Falsemeans not egress) on 5432 from the app group's ID. No egress row means the database host cannot open outbound connections.
08. Step 7: Test the egress path from inside, including what must fail
Open a shell on the probe. In the EC2 console, select lab-probe and choose Connect, then Session Manager; or run aws ssm start-session --target <probe id> if you have the Session Manager plugin for the AWS CLI installed. The agent can take two or three minutes after boot to register. Then run three tests: one that must succeed and two that must fail.
# 1. Allowed: HTTPS out. The address you see is the one the internet sees.
curl -sS -m 10 https://checkip.amazonaws.com
# 2. Not allowed: plain HTTP (port 80) has no egress rule.
curl -sS -m 5 -o /dev/null http://checkip.amazonaws.com; echo "exit=$?"
# 3. No public address on the probe itself (IMDSv2 needs a token).
TOKEN=$(curl -sS -X PUT http://169.254.169.254/latest/api/token \
-H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -sS -o /dev/null -w "%{http_code}\n" -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/public-ipv4203.0.113.10
curl: (28) Connection timed out after 5001 milliseconds
exit=28
404The first line must equal tofu output -raw nat_public_ip: the probe has no internet address of its own, and its traffic leaves through the NAT gateway. The timeout shows that the security group, not the route, stops port 80, since both ports share the same route. The 404 means the instance has no public IPv4 address. (169.254.169.254 is link-local and not filtered by security groups.)
What this design does not protect against:
- A compromised app tier. No egress on the database group stops connections that start on the database host. An attacker running code on an app server holds the app's database credentials and network path, and can send data out through the NAT gateway. Limit that with a least-privilege database user, an egress allow-list or proxy, and VPC Flow Logs with alerts.
- Connected networks. Private hosts are still reachable from inside the VPC and from networks you attach later (peering, VPN, Transit Gateway); security groups limit that.
- A zone failure without retries. A load balancer stops sending new requests to targets in a failed zone only after their health checks fail (interval times unhealthy threshold). Requests in flight can fail, so clients should retry idempotent requests. And with one NAT gateway, the other AZ loses egress too.
09. Step 8: Tear down with one command
If you are going straight on to lab 7, keep everything running and skip this step: lab 7 adds the database to this folder and ends with the same teardown. Otherwise destroy now, then check that nothing tagged for the lab is left in the region.
tofu destroy
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=Project,Values=cloud-basics-lab \
--query 'ResourceTagMappingList[].ResourceARN'Destroy complete! Resources: 27 destroyed.
[]10. Troubleshooting
11. Check your understanding
12. Apply it
For the skill practice, extend this folder instead of starting a new one:
- Add an internet-facing Application Load Balancer in the two public subnets with the
lab-albgroup, a target group on 8080 and one app instance or container behind it. Check that the target turns healthy and is reachable only through the load balancer. - Make egress survive a zone failure in one of two ways and compare them: a regional NAT gateway (
availability_mode = "regional"withvpc_id, no public subnet; check the routes it needs in the provider docs), or one zonal NAT gateway and one private route table per AZ. Note the extra hourly cost first. - Turn on VPC Flow Logs and find the rejected port-80 attempt from step 7.
- After every change, destroy and re-create the stack once to prove
tofu destroystill works.
13. Review prompt
Without looking back, sketch the network: which route table each subnet uses and where its default route goes, where the zonal NAT gateway sits and why, how a regional NAT gateway would change that, and which security group admits traffic to which. Then explain what each of the three tests in step 7 proves, and name two things this design does not protect against.
References
- Amazon VPC User Guide: subnets for your VPC
- Amazon VPC User Guide: regional NAT gateways for automatic multi-AZ expansion
- Terraform AWS provider: aws_nat_gateway (availability_mode)
- Amazon VPC User Guide: NAT gateways
- Application Load Balancers: availability zones and subnets
- Health checks for Application Load Balancer target groups
- Terraform AWS provider: aws_security_group (default egress rule removal)
- Terraform AWS provider: aws_vpc_security_group_ingress_rule
- AWS Systems Manager Session Manager
- Query for the latest Amazon Linux AMI IDs using Systems Manager Parameter Store
- OpenTofu documentation
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.