Mini Project: A VPC + Database Module in Two Environments
The roadmap's IaC milestone, and the IaC part of the DevOps Capstone: a network module and a database module, composed into two environments, dev and prod, and planned and applied by a pipeline. You will reuse almost every lesson of this course.
The plan
infra/
├── modules/
│ ├── network/ # VPC, public + private subnets, IGW, NAT (shared or per zone), route tables
│ │ └── tests/ # mocked: dev/prod shapes, input validation
│ └── database/ # subnet group, security group, RDS PostgreSQL 17
│ └── tests/ # mocked: private, encrypted, protected in prod
├── live/
│ ├── dev/main.tf # backend + provider + both modules: 10.10.0.0/16, 1 NAT, small DB
│ └── prod/main.tf # 10.20.0.0/16, NAT per zone, Multi-AZ DB with deletion protection
└── pipeline.sh # fmt → test modules → per environment: init, validate, plan, summary, policyRequirements:
- Modules with typed, validated inputs and useful outputs (Designing Clean Modules); no provider configuration inside them.
- The network from A VPC & Subnets and Internet Gateway, NAT & Route Tables: subnets keyed by zone,
nat_per_azdeciding between one and three NAT gateways. - The database from RDS PostgreSQL in Code: private, encrypted, managed master password, protected in production. It accepts PostgreSQL only from the private subnets, wired through the network module's outputs.
- One folder per environment (One Folder per Environment) with its own backend and default tags.
- Tests for both modules with a mocked AWS provider (Testing).
- A pipeline script that runs the same checks locally and in CI, prints a one-line summary per environment and blocks plans that delete a database or a VPC (Plan on Pull Request).
Try building it yourself first; the session below is one complete solution.
The session
The sandbox has no AWS account, so each environment gets an offline_override.tf: an override file that merges dummy keys into the real provider "aws" block. The real configuration stays exactly what you would commit; delete the override files (and keep them out of Git) when you run against AWS.
mkdir -p infra && cd infra
mkdir -p modules/network/tests modules/database live/dev live/prod
# ---------- modules/network ----------
cat > modules/network/versions.tf <<'HCL'
terraform {
required_version = ">= 1.6"
required_providers {
aws = { source = "hashicorp/aws", version = ">= 6.0" }
}
}
HCL
cat > modules/network/variables.tf <<'HCL'
variable "name" {
type = string
description = "Prefix for every resource name, e.g. linkly-prod."
}
variable "cidr" {
type = string
description = "VPC CIDR block."
validation {
condition = can(cidrhost(var.cidr, 0)) && tonumber(split("/", var.cidr)[1]) <= 20
error_message = "cidr must be a valid IPv4 block of /20 or larger."
}
}
variable "azs" {
type = list(string)
description = "Availability zones, at least two."
validation {
condition = length(var.azs) >= 2
error_message = "Use at least two availability zones."
}
}
variable "nat_per_az" {
type = bool
description = "One NAT gateway per zone (true) or one shared (false)."
default = false
}
HCL
cat > modules/network/main.tf <<'HCL'
locals {
az_index = { for i, az in var.azs : az => i }
nat_azs = var.nat_per_az ? var.azs : [var.azs[0]]
}
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" }
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.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_eip" "nat" {
for_each = toset(local.nat_azs)
domain = "vpc"
}
resource "aws_nat_gateway" "this" {
for_each = toset(local.nat_azs)
allocation_id = aws_eip.nat[each.key].id
subnet_id = aws_subnet.public[each.key].id
depends_on = [aws_internet_gateway.this]
}
resource "aws_route_table" "private" {
for_each = aws_subnet.private
vpc_id = aws_vpc.this.id
route {
cidr_block = "0.0.0.0/0"
nat_gateway_id = aws_nat_gateway.this[var.nat_per_az ? each.key : var.azs[0]].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
}
HCL
cat > modules/network/outputs.tf <<'HCL'
output "vpc_id" {
description = "VPC id."
value = aws_vpc.this.id
}
output "private_subnet_ids" {
description = "Private subnet ids, in zone order."
value = [for az in var.azs : aws_subnet.private[az].id]
}
output "private_subnet_cidrs" {
description = "Private subnet CIDR blocks, in zone order."
value = [for az in var.azs : aws_subnet.private[az].cidr_block]
}
output "nat_gateway_count" {
description = "Number of NAT gateways."
value = length(aws_nat_gateway.this)
}
HCL
cat > modules/network/tests/network.tftest.hcl <<'HCL'
mock_provider "aws" {}
variables {
name = "test"
cidr = "10.30.0.0/16"
azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
}
run "dev_shape" {
command = plan
assert {
condition = length(aws_nat_gateway.this) == 1 && length(aws_subnet.private) == 3
error_message = "dev: one NAT gateway, three private subnets"
}
}
run "prod_shape" {
command = plan
variables {
nat_per_az = true
}
assert {
condition = length(aws_nat_gateway.this) == 3
error_message = "prod: one NAT gateway per zone"
}
}
run "rejects_tiny_vpc" {
command = plan
variables {
cidr = "10.30.0.0/24"
}
expect_failures = [var.cidr]
}
HCL
# ---------- modules/database ----------
cat > modules/database/versions.tf <<'HCL'
terraform {
required_version = ">= 1.6"
required_providers {
aws = { source = "hashicorp/aws", version = ">= 6.0" }
}
}
HCL
cat > modules/database/main.tf <<'HCL'
variable "name" {
type = string
}
variable "vpc_id" {
type = string
}
variable "subnet_ids" {
type = list(string)
}
variable "allowed_cidrs" {
type = list(string)
description = "Who may connect to PostgreSQL (the private subnets)."
}
variable "production" {
type = bool
default = false
}
resource "aws_db_subnet_group" "this" {
name = var.name
subnet_ids = var.subnet_ids
}
resource "aws_security_group" "db" {
name = "${var.name}-db"
description = "PostgreSQL for ${var.name}"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "postgres" {
for_each = toset(var.allowed_cidrs)
security_group_id = aws_security_group.db.id
cidr_ipv4 = each.value
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
resource "aws_db_instance" "this" {
identifier = var.name
engine = "postgres"
engine_version = "17"
instance_class = var.production ? "db.m7g.large" : "db.t4g.micro"
allocated_storage = 20
max_allocated_storage = var.production ? 200 : 50
storage_type = "gp3"
storage_encrypted = true
db_name = "linkly"
username = "linkly_admin"
manage_master_user_password = true
db_subnet_group_name = aws_db_subnet_group.this.name
vpc_security_group_ids = [aws_security_group.db.id]
publicly_accessible = false
multi_az = var.production
backup_retention_period = var.production ? 14 : 1
deletion_protection = var.production
skip_final_snapshot = !var.production
final_snapshot_identifier = var.production ? "${var.name}-final" : null
apply_immediately = !var.production
}
output "endpoint" {
value = aws_db_instance.this.address
}
HCL
mkdir -p modules/database/tests
cat > modules/database/tests/database.tftest.hcl <<'HCL'
mock_provider "aws" {}
variables {
name = "test"
vpc_id = "vpc-0123456789abcdef0"
subnet_ids = ["subnet-0aaa1111bbbb22223", "subnet-0ccc3333dddd44445"]
allowed_cidrs = ["10.30.16.0/20", "10.30.32.0/20"]
}
run "never_public_always_encrypted" {
command = plan
assert {
condition = !aws_db_instance.this.publicly_accessible && aws_db_instance.this.storage_encrypted
error_message = "the database must be private and encrypted"
}
}
run "production_is_protected" {
command = plan
variables {
production = true
}
assert {
condition = aws_db_instance.this.deletion_protection && aws_db_instance.this.multi_az && !aws_db_instance.this.skip_final_snapshot
error_message = "production needs deletion protection, Multi-AZ and a final snapshot"
}
}
HCL
# ---------- live/<env> ----------
for env in dev prod; do
if [ "$env" = prod ]; then cidr=10.20.0.0/16; nat=true; prodflag=true; else cidr=10.10.0.0/16; nat=false; prodflag=false; fi
cat > live/$env/main.tf <<HCL
terraform {
required_version = ">= 1.6"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
backend "local" {
path = "../../state/$env.tfstate" # in production: the $env account's S3 bucket, use_lockfile = true
}
}
provider "aws" {
region = "eu-west-1"
default_tags {
tags = { Project = "linkly", Environment = "$env", ManagedBy = "opentofu" }
}
}
locals {
name = "linkly-$env"
azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
}
module "network" {
source = "../../modules/network"
name = local.name
cidr = "$cidr"
azs = local.azs
nat_per_az = $nat
}
module "database" {
source = "../../modules/database"
name = local.name
vpc_id = module.network.vpc_id
subnet_ids = module.network.private_subnet_ids
allowed_cidrs = module.network.private_subnet_cidrs
production = $prodflag
}
output "nat_gateways" {
value = module.network.nat_gateway_count
}
HCL
done
# The sandbox has no AWS account: an override file adds dummy keys to the provider block (never commit this).
for env in dev prod; do
cat > live/$env/offline_override.tf <<'HCL'
provider "aws" {
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
done
mkdir -p state
# ---------- the pipeline ----------
cat > pipeline.sh <<'SH'
#!/usr/bin/env bash
# pipeline.sh: what CI runs on a pull request. Lint and test once, then plan every environment.
set -euo pipefail
step() { echo "::: $*"; }
step "fmt"; tofu fmt -check -recursive
for m in modules/network modules/database; do
step "test $m"
tofu -chdir=$m init -input=false >/dev/null
tofu -chdir=$m test | tail -1
done
for env in dev prod; do
dir=live/$env
step "plan $env"
tofu -chdir=$dir init -input=false >/dev/null
tofu -chdir=$dir validate >/dev/null
tofu -chdir=$dir plan -input=false -out=tfplan | grep '^Plan:'
tofu -chdir=$dir show -json tfplan > $dir/plan.json
jq -r --arg env "$env" '
[.resource_changes[] | select(.type == "aws_db_instance") | .change.after][0] as $db
| " \($env): NAT gateways=\([.resource_changes[] | select(.type == "aws_nat_gateway")] | length)"
+ ", db=\($db.instance_class), multi_az=\($db.multi_az), deletion_protection=\($db.deletion_protection)"' $dir/plan.json
if jq -e '[.resource_changes[] | select(.change.actions | index("delete")) | select(.type | test("db_instance|vpcquot;))] | length > 0' $dir/plan.json >/dev/null; then
echo " BLOCKED: $env plan deletes a database or VPC"; exit 3
fi
done
step "all plans ok: ready for review"
SH
chmod +x pipeline.sh
./pipeline.sh::: fmt
::: test modules/network
Success! 3 passed, 0 failed.
::: test modules/database
Success! 2 passed, 0 failed.
::: plan dev
Plan: 26 to add, 0 to change, 0 to destroy.
dev: NAT gateways=1, db=db.t4g.micro, multi_az=false, deletion_protection=false
::: plan prod
Plan: 30 to add, 0 to change, 0 to destroy.
prod: NAT gateways=3, db=db.m7g.large, multi_az=true, deletion_protection=true
::: all plans ok: ready for review
Walkthrough
- Composition in the root.
live/<env>/main.tfcalls both modules and passes the network's outputs (vpc_id,private_subnet_ids,private_subnet_cidrs) into the database. The modules don't know about each other, so each can be tested and versioned alone. - Differences are data. dev and prod differ only in the environment name (backend path, tags, resource names), the CIDR,
nat_per_azandproduction.diff live/dev/main.tf live/prod/main.tfis the complete list of environment differences, which is what a reviewer wants. - The summary line per environment turns two 26- and 30-resource plans into the facts that matter: NAT gateways, database size, Multi-AZ, deletion protection. Post it at the top of the pull-request comment, above the full plans.
- The policy fails the pipeline on any plan that deletes or replaces a database or VPC. Such a change is then done deliberately: a separate pull request, an explicit override, a snapshot first.
prodhas 4 more resources than dev: two more NAT gateways and their Elastic IPs.
The pipeline in GitHub Actions
Pull requests plan both environments in parallel with read-only roles; merging applies dev automatically and prod after approval:
# .github/workflows/infra.yml
name: infra
on:
pull_request:
paths: ["infra/**"]
push:
branches: [main]
paths: ["infra/**"]
permissions:
contents: read
id-token: write
pull-requests: write
jobs:
checks:
runs-on: ubuntu-latest
defaults: { run: { working-directory: infra } }
steps:
- uses: actions/checkout@v7
- uses: opentofu/setup-opentofu@v2
with: { tofu_version: 1.13.2, tofu_wrapper: false }
- run: tofu fmt -check -recursive
- run: for m in modules/*; do tofu -chdir=$m init -input=false && tofu -chdir=$m test; done
plan:
if: github.event_name == 'pull_request'
needs: checks
strategy:
matrix:
env: [dev, prod]
runs-on: ubuntu-latest
defaults: { run: { working-directory: infra/live/${{ matrix.env }} } }
steps:
- uses: actions/checkout@v7
- uses: opentofu/setup-opentofu@v2
with: { tofu_version: 1.13.2, tofu_wrapper: false }
- uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: ${{ vars[format('PLAN_ROLE_{0}', matrix.env)] }} # read-only, per account
aws-region: eu-west-1
- run: tofu init -input=false
- run: tofu plan -input=false -lock-timeout=5m -out=tfplan
- run: tofu show -no-color tfplan > plan-${{ matrix.env }}.txt
- uses: actions/upload-artifact@v7
with: { name: "plan-${{ matrix.env }}", path: "infra/live/${{ matrix.env }}/plan-${{ matrix.env }}.txt" }
apply:
if: github.event_name == 'push'
needs: checks
strategy:
max-parallel: 1 # dev first, then prod
matrix:
env: [dev, prod]
environment: ${{ matrix.env }} # "prod" requires approval
concurrency: { group: "infra-${{ matrix.env }}", cancel-in-progress: false }
runs-on: ubuntu-latest
defaults: { run: { working-directory: infra/live/${{ matrix.env }} } }
steps:
- uses: actions/checkout@v7
- uses: opentofu/setup-opentofu@v2
with: { tofu_version: 1.13.2, tofu_wrapper: false }
- uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: ${{ vars[format('APPLY_ROLE_{0}', matrix.env)] }}
aws-region: eu-west-1
- run: tofu init -input=false
- run: tofu plan -input=false -lock-timeout=5m -out=tfplan
- run: tofu apply -input=false tfplanIn the real repository, pipeline.sh replaces the inline steps so local runs and CI stay identical, and each live/<env> has an S3 backend in that environment's account instead of the local path.
Applying it for real
With an AWS account (budget for NAT gateways and RDS by the hour; check current pricing), the apply of dev looks like this. A sample session:
$ cd live/dev && rm offline_override.tf
$ tofu init && tofu apply
…
module.network.aws_vpc.this: Creating...
module.network.aws_vpc.this: Creation complete after 2s [id=vpc-0d4c3b2a1f0e98765]
…
module.network.aws_nat_gateway.this["eu-west-1a"]: Still creating... [01m30s elapsed]
module.network.aws_nat_gateway.this["eu-west-1a"]: Creation complete after 1m44s [id=nat-0a9b8c7d6e5f43210]
…
module.database.aws_db_instance.this: Still creating... [06m10s elapsed]
module.database.aws_db_instance.this: Creation complete after 6m22s [id=db-7HXZQ2KJ4LMN5PQRSTUVWXYZAB]
Apply complete! Resources: 26 added, 0 changed, 0 destroyed.
Outputs:
nat_gateways = 1
$ tofu plan
…
No changes. Your infrastructure matches the configuration.
$ tofu destroy # the same day, unless you continue with the capstoneExtend it
- Add tflint with the AWS ruleset to
pipeline.sh(tflint --chdir=modules/network, …) and make the pipeline fail on errors only. - Move the modules to their own Git repository, tag
v1.0.0, and pinlive/prodto it with?ref=v1.0.0whilelive/devtriesv1.1.0(Module Sources). - Add S3 and DynamoDB gateway endpoints to the network module so that traffic skips the NAT gateways.
- Switch the backends to S3 with
use_lockfile = true, bootstrap the bucket with its own small configuration, and migrate the state withinit -migrate-state(Migrating State). - Encrypt state and plans with OpenTofu's
aws_kmskey provider (State Encryption). - Add an EKS cluster module that uses the private subnets (EKS in Code): that is the capstone's full IaC layer.
Test yourself
Why does the database module take vpc_id, subnet_ids and allowed_cidrs as inputs instead of looking up the network itself?
- Modules can't use data sources
- Composition: the root passes one module's outputs to the other, so each module stays independent, testable and reusable
- To make the plan shorter
- RDS requires it
What is the purpose of the offline_override.tf files in this project's session?
- They configure production credentials
- They merge dummy credentials into the real provider block so the sandbox can plan without AWS; they are never committed
- They replace the modules
- They encrypt the state
Why does the apply job use max-parallel: 1 with the matrix [dev, prod]?
- GitHub limits matrices
- So dev is applied (and proven) before prod starts, and prod waits for its approval
- To save runner minutes
- Because both share one state