Module 9: Infrastructure as Code with Terraform — The Complete Guide
Goal
In Module 8 you clicked infrastructure together in the AWS console. That doesn't scale, can't be reviewed, and can't be reproduced. Terraform turns infrastructure into versioned, reviewable, repeatable code — the same Git+PR workflow you use for applications, applied to servers and networks.
1. Why IaC — The Problems It Kills
ClickOps failure modes (all real, all common):
- Snowflake environments: staging was built by hand in March, prod in June, by different people. They differ in ways nobody knows — until a deploy works in staging and dies in prod.
- No audit trail: "who opened port 22 to the world, and when?" The console shrugs.
- Disaster recovery = archaeology: rebuild a region from memory? Weeks.
- No review: one admin's misclick deletes a production security group at 4 PM Friday.
With Terraform: infrastructure is .tf files in Git. Changes go through PRs (reviewed!), terraform plan shows exactly what will change before it happens, environments are stamped from the same code, and rebuilding everything is terraform apply. Git history is the audit log.
Analogy
Hand-built infrastructure is a house with no blueprints: every wall is a surprise, and nobody remembers why that one pipe exists. Terraform makes your .tf files the architectural blueprint — the building could burn down and be rebuilt identically tomorrow, and every proposed change is a revision to the drawings that others review before anyone swings a hammer.
Declarative, not imperative: you write the desired end state ("one VPC, two subnets, one ALB"), and Terraform computes the steps — like Kubernetes manifests, unlike bash scripts.
Terraform vs Ansible (recap): Terraform provisions infrastructure (creates the VM, network, LB); Ansible configures inside machines (packages, files). They meet in the middle; container workflows shrink Ansible's role (the Dockerfile is the config), but both remain everywhere.
2. HCL Basics & the Core Workflow
# main.tf
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
# "aws_instance" = resource TYPE, "web" = local NAME (your reference handle)
ami = "ami-0e2c8caa4b6378d8c"
instance_type = "t3.micro"
tags = { Name = "web-server", Env = "dev" }
}The sacred loop:
terraform init # download providers, set up backend (once per project)
terraform plan # DIFF: what would change? (+ create, ~ modify, - destroy)
terraform apply # execute the plan (prompts for confirmation)
terraform destroy # tear everything down (labs love this; prod fears it)
terraform fmt # auto-format
terraform validate # syntax/type check (put in CI)plan is the superpower. Reading plans carefully is the core skill: a -/+ destroy and then create replacement line on a database means data loss — the plan told you before it happened. Never apply a plan you haven't read.
Analogy
Running terraform plan is receiving the contractor's itemized quote before any digging starts: this wall will be added, that one repainted, that one demolished. If the quote casually lists demolishing the room where the family archives are kept, you want to spot that line while it is still just paper.
References & implicit dependencies
resource "aws_security_group" "web" {
name = "web-sg"
vpc_id = aws_vpc.main.id # ← reference: TYPE.NAME.ATTRIBUTE
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web.id] # ← creates ordering
}References build a dependency graph — Terraform creates the VPC before the SG before the instance, automatically, and parallelizes everything independent. (Rarely, depends_on = [...] forces ordering Terraform can't infer.)
3. State — The Concept That Makes or Breaks You
Terraform stores a mapping of your code ↔ real resource IDs in state (terraform.tfstate). Plan = three-way comparison: code (desired) vs state (last known) vs reality (refreshed via API).
Analogy
State is the official building registry at city hall: it records which real, standing structures your blueprints correspond to. Lose the registry and the city forgets your blueprints ever matched those buildings — the next construction crew shows up and starts erecting duplicates on the lot next door.
Why it's critical:
- Lose state → Terraform forgets it owns anything → next apply tries to create duplicates or you're back to manual cleanup.
- State contains secrets in plaintext (DB passwords, etc.) → never commit it to Git (
.gitignoreit), encrypt it at rest. - Two people applying simultaneously → corrupted state.
Remote state + locking — mandatory for teams (and this outline's "different backends")
terraform {
backend "s3" {
bucket = "myco-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks" # lock: second runner waits/fails cleanly
encrypt = true
}
}Backends = where state lives: local (default, laptops/labs), S3+DynamoDB (AWS standard), Terraform Cloud/HCP (managed, free tier), GCS/AzureRM (other clouds), Consul. Migrating: change the block, terraform init -migrate-state.
Also split state per concern (network/, app/, db/ with separate keys) — smaller blast radius, faster plans, teams don't lock each other.
State surgery (careful, but you WILL need these)
terraform state list # what does TF think it owns?
terraform state show aws_instance.web # details of one
terraform state mv aws_instance.web aws_instance.frontend # refactor code w/o destroy
terraform state rm aws_instance.legacy # forget (not destroy) a resourceImporting existing infrastructure
Real scenario — you join a company with 100% click-created AWS. You don't rebuild; you adopt:
import {
to = aws_instance.web
id = "i-0abc123456789def0"
}terraform plan -generate-config-out=generated.tf # TF writes matching code!
terraform apply # now managed; plan shows no changes(Older syntax: terraform import aws_instance.web i-0abc... after hand-writing the resource.) Importing a brownfield estate piece by piece is genuine senior-level work — and it starts exactly like this.
Analogy
Importing is registering buildings that were put up before the registry existed. You walk each standing structure, file its paperwork at city hall, and draw a blueprint that matches what is already built — nothing gets demolished, it is simply brought under proper record-keeping, one building at a time.
4. Variables, Outputs, Locals
# variables.tf — the inputs (knobs)
variable "env" {
type = string
description = "Environment name"
validation {
condition = contains(["dev", "staging", "prod"], var.env)
error_message = "env must be dev, staging, or prod."
}
}
variable "instance_count" {
type = number
default = 2
}
variable "db_password" {
type = string
sensitive = true # redacted in output
}
# locals — computed values / DRY
locals {
name_prefix = "myapp-${var.env}"
common_tags = { Project = "myapp", Env = var.env, ManagedBy = "terraform" }
}
# outputs.tf — the return values
output "alb_dns_name" {
value = aws_lb.main.dns_name
description = "Point your DNS at this"
}Supplying values (precedence low→high): defaults → terraform.tfvars → *.auto.tfvars → -var-file=prod.tfvars → -var flags → TF_VAR_db_password env vars (the CI-friendly way for secrets).
Per-environment pattern: one codebase + dev.tfvars / prod.tfvars (small counts and sizes in dev, big in prod) — same shape, different scale. Workspaces (terraform workspace new staging) give separate state files per env with one backend; fine for small setups, though many teams prefer separate directories/state keys per env for explicitness.
Analogy
Variables make the blueprint parametric: one set of drawings with blank fields for lot size and number of floors. The dev neighborhood fills in a small cottage, prod fills in the full tower — same rooms, same wiring diagram, different scale, and nobody has to maintain two slowly diverging sets of drawings.
5. Loops & Expressions
# count — N identical things (indexed list)
resource "aws_instance" "web" {
count = var.instance_count
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
tags = { Name = "web-${count.index}" }
}
# refer: aws_instance.web[0].id, aws_instance.web[*].id
# for_each — a map of distinct things (keyed, the usual better choice)
resource "aws_subnet" "private" {
for_each = { a = "10.0.11.0/24", b = "10.0.12.0/24" }
vpc_id = aws_vpc.main.id
cidr_block = each.value
availability_zone = "us-east-1${each.key}"
tags = { Name = "private-${each.key}" }
}Why for_each > count for non-identical sets: delete the middle item of a count list and every later index shifts — Terraform plans to destroy/recreate innocent resources. for_each keys are stable. This bites every team exactly once.
Analogy
Count is numbering hotel rooms by their position in the row: knock down room 2 and rooms 3, 4, and 5 all get renumbered, so the builders tear them down and rebuild them just to fix the signs. for_each gives every room a permanent name on the door — remove one and its neighbors are untouched.
Also: conditionals var.env == "prod" ? 3 : 1, for expressions [for s in aws_subnet.private : s.id], and dynamic blocks for repeated nested blocks (e.g., generating many ingress rules from a list).
Data sources — read, don't manage
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-noble-24.04-amd64-server-*"]
}
}
data "aws_caller_identity" "current" {} # who am I / account ID
# and: terraform_remote_state to read another stack's outputs (app reads network's subnet IDs)Provisioners — the escape hatch (use sparingly)
provisioner "remote-exec" / "file" run commands/copy files on a resource at create time. Official guidance: last resort — not idempotent, brittle. Prefer user_data/cloud-init, baked AMIs (Packer), or Ansible. Know the one legitimately useful one: local-exec for glue (e.g., write an Ansible inventory after creating instances — a classic Terraform→Ansible handoff).
6. Modules — Reusable Infrastructure Components
A module = a folder of .tf files with variables in and outputs out — a function for infrastructure.
# envs/prod/main.tf
module "api" {
source = "../../modules/web-service"
name = "api"
image = "1234.dkr.ecr.us-east-1.amazonaws.com/api:v2.3.1"
desired_count = 3
vpc_id = module.network.vpc_id
}
module "network" {
source = "terraform-aws-modules/vpc/aws" # public registry module
version = "5.8.1" # ALWAYS pin versions
cidr = "10.0.0.0/16"
# ... the entire Module-4 VPC design in ~15 lines
}Registry modules (registry.terraform.io) encode community best practice — the vpc module builds subnets, NAT, route tables correctly so you don't hand-roll them every time. Write your own modules when a pattern repeats twice; keep them small and single-purpose; pin everything.
Analogy
A module is a reusable room design in the architect's catalog: a proven kitchen layout with labeled inputs (dimensions, finishes) and known outputs (where the plumbing exits). Registry modules are the published catalog that thousands of builders have already stress-tested, so you stop drawing staircases from scratch on every project.
7. Terraform in CI/CD & Atlantis
Infrastructure changes deserve the same pipeline as code:
# GitHub Actions sketch
on: pull_request
jobs:
plan:
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform fmt -check && terraform validate
- run: terraform plan -no-color -out=tfplan
# post the plan as a PR comment; apply job runs on merge with environment approvalAdd static analysis: tflint (linting), trivy/checkov (misconfig scanning: "S3 bucket is public", "SG open to 0.0.0.0/0 on 22") — infrastructure code gets security review by robots too.
Atlantis — the purpose-built GitOps workflow for Terraform. A small server listens to your Git webhooks:
- You open a PR changing
.tffiles → Atlantis runsterraform planand comments the plan on the PR. - Team reviews code and plan together.
- A reviewer comments
atlantis apply→ Atlantis applies, comments results, PR merges.
What this buys: nobody runs Terraform from laptops (no credential sprawl, no "which version?"), every change has a reviewed plan attached forever, state locking is respected, and apply rights become Git permissions. (HCP Terraform / Spacelift / env0 are managed alternatives with the same shape.)
Analogy
Atlantis is the site office where every renovation request gets pinned to the noticeboard with its full contractor quote attached. No builder works from plans kept loose in their own truck; work begins only after a named reviewer signs the quote, and the signed paperwork stays stapled to the request forever.
8. Best Practices Checklist (Interview-Ready)
- Remote state, encrypted, locked, never in Git.
- Small plans read fully before apply; treat
destroy and recreateon stateful resources as an alarm. Guardrails:lifecycle { prevent_destroy = true }on databases;create_before_destroywhere replacement is legit. - Pin versions — providers, modules, Terraform itself (
required_version). - No secrets in code or state where avoidable — pass at runtime (
TF_VAR_), or better, have resources pull from Secrets Manager/SSM; mark variablessensitive. - Structure: split states by layer (network / data / app) and env; consistent
main.tf/variables.tf/outputs.tf;terraform fmtenforced in CI. - Everything through PR + plan review (Atlantis/CI) — console changes are drift; detect drift with scheduled
terraform plan(non-empty diff = someone clicked). - Tag everything (
ManagedBy = "terraform", Env, Owner, CostCenter) — cost reports and "can I delete this?" both depend on tags. - Modules for repetition, registry modules for solved problems.
Analogy
Drift is a tenant renovating without updating the blueprint: the drawings say two windows, the wall now has three. A scheduled terraform plan is the inspector walking the building with the drawings in hand — any mismatch means someone changed the real world without filing the paperwork.
9. Hands-On Project (Do This) — Rebuild Module 8 as Code
- Bootstrap: S3 state bucket + DynamoDB lock table (create these once by CLI/console — the chicken-and-egg exception), configure the backend.
- Network module: use
terraform-aws-modules/vpc/awsto build the Module-4 VPC (2 public + 2 private subnets, NAT). Output subnet IDs. - App stack (separate state, reads network via
terraform_remote_state): ECR repo, ALB, ECS Fargate service, SG chain (alb-sg → app-sg), all tagged vialocal.common_tags, image tag as a variable. - Two envs from the same code:
dev.tfvars(1 task, no NAT to save money) andprod.tfvars(2 tasks, 2 AZs). Apply dev; plan prod and just read it. - Practice the scary skills: rename a resource and fix with
state mv; create a bucket in the console, thenimportit; make a manual console change and catch the drift withplan. - Wire CI: fmt/validate/tflint/trivy + plan-on-PR (GitHub Actions with OIDC role from Module 8). Bonus: run Atlantis locally in Docker against a test repo and feel the
atlantis plan/applyflow. terraform destroydev completely; confirm $0 on the billing page. (This — one-command teardown — is the everyday miracle of IaC.)
10. Self-Check Questions
- What are the three things
plancompares? Why is losing state catastrophic? - Why S3 + DynamoDB specifically — what does each provide?
countvsfor_each— describe the index-shift failure concretely.- The plan shows
-/+ aws_db_instance.main (destroy and then create replacement). What do you do before typing "yes"? - How do you bring a hand-made resource under Terraform without recreating it?
- Where should secrets live relative to Terraform code and state?
- What problem does Atlantis solve that plain CI plan/apply doesn't fully?
- Terraform vs Ansible in one sentence each.
Next → Module 10: Monitoring & Logging
