DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 17 of 17
Your progress · 0%
On this page
  1. The project layout
  2. The VPC module
  3. The load balancer and the app
  4. Environments and remote state
  5. Track A: prove it for free
  6. Track B: apply to AWS (optional)
  7. Ship it
↖ Course roadmap
Lesson 17 · Capstone project

Capstone: AWS infrastructure with Terraform

Build a real AWS stack end to end: VPC, load balancer, Auto Scaling, IAM, remote state and two environments from shared modules. A free local track proves it all; the AWS track is optional.

60 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

Verified lab: Track A in full: fmt, TFLint, Trivy, terraform test with a mocked AWS provider and offline plans of dev (27 resources) and prod (30), on Terraform 1.17.1 with AWS provider 6.72.0. The output shown is real.
Code walkthrough: the GitHub Actions workflow (lesson 13's pattern): explained, not run.
Cloud lab: Track B, applying to AWS, needs an account and costs money. It wasn't applied for this course.

Sixteen lessons of concepts come together here in one project: the kind of thing a team builds in its first month on AWS, and the kind of thing to show in an interview. A startup wants a web app behind a load balancer, in dev and prod, built the same way every time.

You can complete it two ways. Track A is free: it builds and proves the whole project without an AWS account, and every output below comes from it. Track B is optional: it applies the same code to real AWS, which costs money, with a budget, a short checklist and verified cleanup.

Only the load balancer faces the internet. The app lives in private subnets and only accepts traffic from the ALB.© Diagram: DevOps Academy

Only the load balancer faces the internet. The app lives in private subnets and only accepts traffic from the ALB.© Diagram: DevOps Academy

The project layout

shop/
├── modules/
│   ├── vpc/                 # VPC, 2 public + 2 private subnets, routes, optional NAT
│   ├── security-groups/     # ALB and app security groups
│   ├── app/                 # IAM role, launch template, Auto Scaling group
│   └── alb/                 # load balancer, target group, listener
├── environments/
│   ├── dev/                 # main.tf, variables.tf, backend.tf, dev.tfvars
│   └── prod/                # same files, prod.tfvars
├── bootstrap/
│   └── state-backend/       # the S3 state bucket, applied once with local state
├── tests/                   # terraform test files with a mocked AWS provider
├── .github/workflows/       # plan on PR, apply the saved plan after approval
├── .tflint.hcl
├── .gitignore
└── README.md

Every concept from the course has a place: modules (lesson 10), environments as folders (12), remote state with locking (8), validation (6), lifecycle rules (5), tests (14), CI/CD (13) and scanning (16).

The VPC module

The network: one VPC, a public and a private subnet in each of two Availability Zones, an internet gateway for the public side, and an optional NAT gateway for the private side.

# modules/vpc/main.tf (excerpt)
variable "cidr" {
  description = "VPC address range, e.g. 10.10.0.0/16."
  type        = string

  validation {
    condition     = can(cidrnetmask(var.cidr)) && tonumber(split("/", var.cidr)[1]) <= 20
    error_message = "cidr must be a valid IPv4 range of /20 or larger, e.g. 10.10.0.0/16."
  }
}

variable "enable_nat_gateway" {
  description = "One NAT gateway so private subnets can reach the internet. Billed by the hour: off by default."
  type        = bool
  default     = false
}

# Public subnets: 10.10.0.0/24, 10.10.1.0/24 ... (one per AZ)
resource "aws_subnet" "public" {
  count = length(var.azs)

  vpc_id            = aws_vpc.this.id
  availability_zone = var.azs[count.index]
  cidr_block        = cidrsubnet(var.cidr, 8, count.index)
  tags              = { Name = "${var.name}-public-${var.azs[count.index]}" }
}

# Private subnets: 10.10.10.0/24, 10.10.11.0/24 ...
resource "aws_subnet" "private" {
  count = length(var.azs)

  vpc_id            = aws_vpc.this.id
  availability_zone = var.azs[count.index]
  cidr_block        = cidrsubnet(var.cidr, 8, count.index + 10)
  tags              = { Name = "${var.name}-private-${var.azs[count.index]}" }
}

resource "aws_nat_gateway" "this" {
  count         = var.enable_nat_gateway ? 1 : 0
  allocation_id = aws_eip.nat[0].id
  subnet_id     = aws_subnet.public[0].id
  tags          = { Name = var.name }

  depends_on = [aws_internet_gateway.this]
}

Design decisions worth explaining in an interview:

  • cidrsubnet instead of typed ranges. Subnets are carved from the VPC range, so changing the VPC CIDR in prod.tfvars moves every subnet with it. The offline plan confirms the layout: 10.10.0.0/24 and 10.10.1.0/24 public, 10.10.10.0/24 and 10.10.11.0/24 private.
  • The NAT gateway is opt-in. It's billed by the hour even when idle, and the app doesn't need the internet: it serves its page with Python's built-in server, so there's nothing to download. Dev runs without one; prod turns it on for OS updates.
  • One NAT gateway, not one per AZ. That's a single point of failure for outbound traffic, chosen to keep cost down. Production at scale uses one per AZ.
  • depends_on on the NAT gateway is one of the rare hidden dependencies from lesson 5: AWS needs the internet gateway attached first, and nothing in the NAT's arguments refers to it.
  • Validation rejects a VPC smaller than /20 (no room for the subnets) and fewer than two AZs.

The load balancer and the app

The security groups encode "only the load balancer faces the internet":

# modules/security-groups/main.tf (excerpt)
resource "aws_vpc_security_group_ingress_rule" "alb_http" {
  security_group_id = aws_security_group.alb.id
  description       = "HTTP from the internet"
  cidr_ipv4         = "0.0.0.0/0"
  from_port         = 80
  to_port           = 80
  ip_protocol       = "tcp"
}

resource "aws_vpc_security_group_ingress_rule" "app_from_alb" {
  security_group_id            = aws_security_group.app.id
  description                  = "App port, from the ALB only"
  referenced_security_group_id = aws_security_group.alb.id
  from_port                    = var.app_port
  to_port                      = var.app_port
  ip_protocol                  = "tcp"
}

The app's rule references the ALB's security group, not an IP range, so it stays correct however the load balancer's addresses change. Each rule is its own resource (aws_vpc_security_group_ingress_rule), the current recommended style, rather than inline blocks.

The app module runs the instances with an Auto Scaling group:

# modules/app/main.tf (excerpt)
resource "aws_launch_template" "app" {
  name_prefix            = "${var.name}-app-"
  image_id               = var.ami_id
  instance_type          = var.instance_type
  vpc_security_group_ids = [var.security_group_id]

  iam_instance_profile {
    name = aws_iam_instance_profile.app.name
  }

  # Serves a page with Python's built-in server: no packages to install, so no internet needed
  user_data = base64encode(templatefile("${path.module}/user-data.sh.tftpl", {
    name = var.name
    port = var.app_port
  }))

  metadata_options {
    http_tokens = "required" # IMDSv2 only
  }

  block_device_mappings {
    device_name = "/dev/xvda"
    ebs {
      volume_size = 8
      volume_type = "gp3"
      encrypted   = true
    }
  }
}

resource "aws_autoscaling_group" "app" {
  name                = "${var.name}-app"
  vpc_zone_identifier = var.subnet_ids
  min_size            = var.min_size
  max_size            = var.max_size
  desired_capacity    = var.min_size
  target_group_arns   = [var.target_group_arn]
  health_check_type   = "ELB"

  launch_template {
    id      = aws_launch_template.app.id
    version = "$Latest"
  }
}
  • IAM role with AmazonSSMManagedInstanceCore: you reach instances with SSM Session Manager, so there's no SSH key and no port 22. (SSM from private subnets needs the NAT gateway or VPC endpoints.)
  • templatefile for user data (lesson 11) renders the startup script with the site name and port.
  • IMDSv2 and an encrypted root disk answer two of the Trivy findings from lesson 16 by default.
  • health_check_type = "ELB" makes the Auto Scaling group replace instances the load balancer marks unhealthy, not just ones that crash.
  • A cost guard: max_size above 6 fails validation, so a typo can't launch 60 instances.

The ALB module creates the load balancer in the public subnets, a target group on port 8080 that health-checks /, and a listener on port 80. HTTPS needs a domain and an ACM certificate, covered as an upgrade at the end.

Environments and remote state

environments/dev and environments/prod are small root modules that call the four modules. They differ only in their tfvars:

# environments/dev/dev.tfvars
env  = "dev"
cidr = "10.10.0.0/16"
# environments/prod/prod.tfvars
env                = "prod"
cidr               = "10.20.0.0/16"
instance_type      = "t3.small"
min_size           = 2
max_size           = 4
enable_nat_gateway = true

The AMI comes from AWS's public SSM parameter for the latest Amazon Linux 2023, looked up with a data source. When ami_id is set (Track A and tests), the lookup is skipped:

# environments/dev/main.tf (excerpt)
data "aws_ssm_parameter" "al2023" {
  count = var.ami_id == null ? 1 : 0
  name  = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}

module "app" {
  source            = "../../modules/app"
  name              = local.name
  ami_id            = local.ami_id
  instance_type     = var.instance_type
  subnet_ids        = module.vpc.private_subnet_ids
  security_group_id = module.security_groups.app_sg_id
  target_group_arn  = module.alb.target_group_arn
  min_size          = var.min_size
  max_size          = var.max_size
}

Each environment has its own state key in the S3 bucket, with native locking:

# environments/prod/backend.tf
terraform {
  backend "s3" {
    bucket       = "REPLACE-WITH-YOUR-STATE-BUCKET" # from bootstrap/state-backend
    key          = "shop/prod/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

The bucket itself is created once by bootstrap/state-backend, with local state, versioning, AES256 encryption, public access blocked, and prevent_destroy. It's the one thing in the project you never destroy casually.

Track A: prove it for free

Everything in this section ran without an AWS account. It's also exactly what CI runs on every pull request.

1. Format, lint and scan

$ terraform fmt -check -recursive
(exit code 0)
$ tflint --recursive --format=compact
4 issue(s) found:

modules/app/main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
modules/security-groups/main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
modules/alb/main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
modules/vpc/main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
(exit code 2)
terraform fmt -check -recursive
  • terraforminfrastructure as code
  • fmtformat the files

TFLint caught a real gap: the modules didn't follow the course's version policy. After adding required_version = ">= 1.11" to each module, the same command exits 0 with no issues.

Trivy at HIGH and CRITICAL reported 0 misconfigurations for every folder. That's because five findings are deliberate and suppressed in code, each with a reason. To see what the suppressions hide, scan a copy with the #trivy:ignore comments removed:

# the same code with every #trivy:ignore comment removed
Failures: 1 (HIGH: 1, CRITICAL: 0)
AWS-0132 (HIGH): Bucket does not encrypt data with a customer managed key.
Failures: 4 (HIGH: 2, CRITICAL: 2)
AWS-0053 (HIGH): Load balancer is exposed publicly.
AWS-0053 (HIGH): Load balancer is exposed publicly.
AWS-0054 (CRITICAL): Listener for application load balancer does not use HTTPS.
AWS-0054 (CRITICAL): Listener for application load balancer does not use HTTPS.
Failures: 2 (HIGH: 0, CRITICAL: 2)
AWS-0104 (CRITICAL): Security group rule allows unrestricted egress to any IP address.
AWS-0104 (CRITICAL): Security group rule allows unrestricted egress to any IP address.

(Findings in modules appear twice because both environments use them.) Each suppression is a decision you can defend:

FindingWhy it's suppressedWhat production would do
AWS-0053 public load balancerIt's the website's front doorAdd AWS WAF in front
AWS-0054 HTTP listenerHTTPS needs a domain and certificateAdd an ACM certificate and an HTTPS listener (below)
AWS-0104 app egress to the internetHTTPS out for updates and SSM via the NATUse VPC endpoints and remove the rule
AWS-0132 state bucket without a KMS keyAES256 keeps the lab freeEncrypt with a customer-managed KMS key

One more ignore comment, for AWS-0107, was removed: the scan without it showed it hid nothing, and an ignore with no finding behind it only hides future mistakes.

2. Test the modules with a mocked AWS provider

mock_provider "aws" {} replaces AWS with fake responses, so apply-mode tests create nothing and cost nothing. The first run failed, which taught something about mocks:

$ terraform test
tests/app.tftest.hcl... in progress
  run "instances_are_hardened"... fail

Error: "launch_template.0.id" must begin with 'lt-' and only contain alphanumeric characters: ej9k4bjo

  with aws_autoscaling_group.app,
  on modules/app/main.tf line 122, in resource "aws_autoscaling_group" "app":
 122:     id      = aws_launch_template.app.id
terraform test
  • terraforminfrastructure as code

Mocks invent random IDs (ej9k4bjo), but the Auto Scaling group validates that a launch template ID starts with lt-. Give the mock a realistic default for that one resource:

# tests/app.tftest.hcl (top)
mock_provider "aws" {
  # Mocks invent random IDs, but the ASG checks launch template IDs start with "lt-"
  mock_resource "aws_launch_template" {
    defaults = {
      id = "lt-0123456789abcdef0"
    }
  }
}
$ terraform test
tests/app.tftest.hcl... in progress
  run "instances_are_hardened"... pass
  run "cost_guard_on_max_size"... pass
tests/app.tftest.hcl... tearing down
tests/app.tftest.hcl... pass
tests/vpc.tftest.hcl... in progress
  run "two_public_and_two_private_subnets"... pass
  run "no_nat_gateway_by_default"... pass
  run "one_nat_gateway_when_enabled"... pass
  run "rejects_a_tiny_cidr"... pass
  run "rejects_a_single_az"... pass
tests/vpc.tftest.hcl... tearing down
tests/vpc.tftest.hcl... pass

Success! 7 passed, 0 failed.
terraform test
  • terraforminfrastructure as code

The seven tests check the design itself: the subnet ranges, that NAT is off unless asked for, IMDSv2 and disk encryption, and that validation rejects a tiny VPC, a single AZ and an oversized Auto Scaling group.

3. Plan both environments offline

terraform plan normally needs credentials. Terraform's override files (any file ending in _override.tf) merge over the real configuration, so a local, git-ignored file can swap in fake credentials and a local backend without touching the real code:

# environments/dev/offline_override.tf (Track A only, git-ignored)
provider "aws" {
  access_key                  = "mock"
  secret_key                  = "mock"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}

# Keep state in a local file instead of the S3 bucket.
terraform {
  backend "local" {}
}

Every resource is new, and passing ami_id skips the two data sources, so the plan makes no AWS calls:

$ terraform init -reconfigure
Successfully configured the backend "local"! ...
$ terraform plan -var-file=dev.tfvars -var="ami_id=ami-0123456789abcdef0" -out=dev.tfplan
  # module.alb.aws_lb.this will be created
  # module.alb.aws_lb_listener.http will be created
  # module.alb.aws_lb_target_group.app will be created
  # module.app.aws_autoscaling_group.app will be created
  # module.app.aws_iam_instance_profile.app will be created
  # module.app.aws_iam_role.app will be created
  # module.app.aws_iam_role_policy_attachment.ssm will be created
  # module.app.aws_launch_template.app will be created
  # module.security_groups.aws_security_group.alb will be created
  # module.security_groups.aws_security_group.app will be created
  ...
  # module.vpc.aws_subnet.private[0] will be created
  # module.vpc.aws_subnet.private[1] will be created
  # module.vpc.aws_subnet.public[0] will be created
  # module.vpc.aws_subnet.public[1] will be created
  # module.vpc.aws_vpc.this will be created
Plan: 27 to add, 0 to change, 0 to destroy.
terraform init -reconfigure
  • terraforminfrastructure as code
  • initdownload providers, set up the folder
terraform plan -var-file=dev.tfvars -var="ami_id=ami-0123456789abcdef0" -out=dev.tfplan
  • planpreview changes

(Trimmed to the resource lines; the real plan lists every attribute.) Prod, from the same modules:

$ terraform plan -var-file=prod.tfvars -var="ami_id=ami-0123456789abcdef0"
  # module.vpc.aws_eip.nat[0] will be created
  # module.vpc.aws_nat_gateway.this[0] will be created
  # module.vpc.aws_route.private_nat[0] will be created
  ...
      + desired_capacity                 = 2
      + max_size                         = 4
      + min_size                         = 2
      + instance_type          = "t3.small"
Plan: 30 to add, 0 to change, 0 to destroy.
terraform plan -var-file=prod.tfvars -var="ami_id=ami-0123456789abcdef0"
  • terraforminfrastructure as code
  • planpreview changes

Thirty, not twenty-seven: the NAT gateway, its Elastic IP and the private route, switched on by one line in prod.tfvars. An offline plan can't prove AWS will accept everything (quotas, names already taken, permissions), which is what Track B is for. It does prove the code is complete, consistent and does what the design says.

Track B: apply to AWS (optional)

This costs money

The Application Load Balancer, the NAT gateway (prod) and the EC2 instances are billed by the hour, even when nobody uses them; check current prices on the AWS pricing pages in Resources. Use a personal or sandbox account, never your employer's production account. Set a budget first, apply dev only, test, and destroy the same day.

  1. Set a budget alarm. In the AWS console, Billing and Cost Management → Budgets → create a monthly cost budget (say $10) with an email alert at 80%. Do this before anything else.

  2. Create the state bucket, once:

    $ cd bootstrap/state-backend && terraform init
    $ terraform apply -var="bucket_name=<your-unique-name>"
    
    cd bootstrap/state-backend && terraform init
    • cdchange directory
    • &&run the next command only if this one worked
    • terraforminfrastructure as code
    • initdownload providers, set up the folder
    terraform apply -var="bucket_name=<your-unique-name>"
    • applymake the changes
  3. Point dev at it. Put the bucket name in environments/dev/backend.tf, delete any offline_override.tf, and run terraform init.

  4. Plan, read, apply.

    $ terraform plan -var-file=dev.tfvars -out=dev.tfplan
    $ terraform apply dev.tfplan
    $ curl "$(terraform output -raw url)"
    
    terraform plan -var-file=dev.tfvars -out=dev.tfplan
    • terraforminfrastructure as code
    • planpreview changes
    terraform apply dev.tfplan
    • applymake the changes
    curl "$(terraform output -raw url)"
    • curlmake an HTTP request

    The instances need two to three minutes to pass health checks. Until then the load balancer answers with a 503 (no healthy targets yet).

  5. Destroy, then verify nothing is left.

    $ terraform destroy -var-file=dev.tfvars
    $ aws elbv2 describe-load-balancers --names shop-dev                  # expect LoadBalancerNotFound
    $ aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names shop-dev-app \
        --query 'AutoScalingGroups[].AutoScalingGroupName'                 # expect []
    $ aws ec2 describe-instances --filters Name=tag:Name,Values=shop-dev-app \
        Name=instance-state-name,Values=running --query 'Reservations[].Instances[].InstanceId'  # expect []
    
    terraform destroy -var-file=dev.tfvars
    • terraforminfrastructure as code
    • destroydelete everything it manages
    aws elbv2 describe-load-balancers --names shop-dev
    • awsthe AWS command line

    If you applied prod, also check that NAT gateways show deleted and no Elastic IP tagged shop-prod-nat remains (aws ec2 describe-nat-gateways, aws ec2 describe-addresses): an Elastic IP left behind is billed. The state bucket stays (prevent_destroy); empty and delete it only when you're finished with the project.

Upgrade: HTTPS

With a domain in Route 53, add an aws_acm_certificate with DNS validation, an HTTPS listener on 443 using it, and change the port-80 listener to redirect to 443. Then the AWS-0054 suppression comes out, and the scan should still pass.

Ship it

The workflow in .github/workflows/terraform.yml is lesson 13's, pointed at environments/dev, with terraform test added before the plan: fmt, TFLint, Trivy, tests and plan on every pull request, and the saved plan applied after approval on main, with OIDC credentials.

A strong portfolio version has:

  • A README with the architecture diagram, both tracks, the cost warning and the cleanup commands.
  • The tests passing in CI, with the badge on the README.
  • No secrets and no state in the repository: check .gitignore covers *.tfstate, plans and *_override.tf.
  • A short design notes section: why private subnets, why one NAT gateway, what each Trivy suppression means and what you'd change for production.
⌘
Mini mission

Build the capstone and prove it for free

Build the shop project: four modules, dev and prod environments, the state-backend bootstrap, tests and CI. Then complete Track A: fmt and TFLint clean, Trivy with no unexplained findings, all terraform tests passing, and offline plans of 27 resources for dev and 30 for prod. Publish it on GitHub with a README. Track B (applying to AWS) is optional.

Input: The layout and module code from this lessonOutput: A public GitHub repository
Reveal one safe solution
$ terraform fmt -check -recursive && tflint --init && tflint --recursive
$ trivy config --quiet --severity HIGH,CRITICAL .
$ terraform init && terraform test
$ cd environments/dev && cp offline_override.tf.example offline_override.tf
$ terraform init -reconfigure && terraform plan -var-file=dev.tfvars -var="ami_id=ami-0123456789abcdef0"
terraform fmt -check -recursive && tflint --init && tflint --recursive
  • terraforminfrastructure as code
  • fmtformat the files
  • &&run the next command only if this one worked
trivy config --quiet --severity HIGH,CRITICAL .
  • .this folder
terraform init && terraform test
  • initdownload providers, set up the folder
cd environments/dev && cp offline_override.tf.example offline_override.tf
  • cdchange directory
  • cpcopy files
terraform init -reconfigure && terraform plan -var-file=dev.tfvars -var="ami_id=ami-0123456789abcdef0"
  • planpreview changes

Your result should match the lab: Success! 7 passed, 0 failed. and Plan: 27 to add for dev (30 for prod). If the plan asks for credentials, the override file is missing or misnamed: it must end in _override.tf. If you write more tests, start each with one that fails.

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 4

Why are the EC2 instances in private subnets?

Go deeper

Official reading for this lesson

  • DocsAWS provider documentationTerraform Registry ↗
  • DocsOverride filesHashiCorp ↗
  • DocsMocks in Terraform testsHashiCorp ↗
  • DocsAWS BudgetsAWS Docs ↗
  • GuideElastic Load Balancing pricingAWS ↗
  • GuideAmazon VPC pricing (NAT gateway)AWS ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousTerraform security: secrets, scanning and policyUp nextBack to the course roadmap