Skip to content
devops/architect
05 terraform 01 01 terraform
0/10 read · lab 0/1
STARTUP TO ENTERPRISE
05 / 14 • INFRASTRUCTURE AS CODE

Terraform

Define your entire cloud estate as code. Learn the plan/apply lifecycle, state management, module composition, remote backends, and how to run production-grade multi-account environments.

Free Tier EC2+RDS EKS + Modules Landing Zone

Lesson objective

What it teaches
Architecture & How It Works · Core Components & Concepts · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Advanced State & Module Patterns · Terragrunt: DRY Multi-Environment IaC · Atlantis + CI Drift Detection · Predict the Result: Plan and Exit Codes
Why it matters
A required lesson for DevOps Engineer, Cloud Engineer, Platform Engineer, FinOps / Cloud Optimization, DevOps / Platform Architect. Recommended for DevSecOps Engineer, Release / CI-CD Engineer. See the role paths
What you demonstrate
  • Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
  • Predict 3 results this lesson prints. You mark each one yourself.
  • Optional, real environment: 11 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

Architecture & How It Works 05.1

Terraform builds a dependency graph (DAG) from your configuration. It compares desired state (config) to actual state (state file), calculates the minimal set of changes, then executes them in order.

graph TD Init[terraform init] --> Plan[terraform plan] Plan --> Refresh[Refresh state from real world] Refresh --> Graph[Build DAG] Graph --> Apply[terraform apply] Apply --> Create[Create/Update/Delete] Create --> Persist[Write state to remote backend] Persist --> Lock[DynamoDB state lock]

Providers are Plugins

Providers are downloaded during init. They translate HCL into API calls. Always pin provider versions.

State is Sacred

State is the only record of what Terraform manages. Never edit it manually. Use remote backends with locking.

Terraform: State is Your God. Don't Irritate It. · 109s

Core Components & Concepts 05.2

ElementPurposeCommon Pattern
resource / dataManage or read infrastructureaws_vpc, data "aws_ami"
moduleReusable, versioned packagesterraform-aws-modules/vpc/aws
variable / output / localInputs, outputs, computed valuesvar.region, output.vpc_id
workspaceIsolate state per environmentdev / staging / prod
backend "s3"Remote state + lockingBucket + DynamoDB table
count / for_each / dynamicMeta-arguments for repetitionCreating N subnets

WSL Hands-On Lab 05.3

Complete VPC + Subnets + EKS-ready + Workspaces + Import

install terraform
$ wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg > /dev/null
$ echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
$ sudo apt update && sudo apt install terraform
main.tf (VPC + subnets)
terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
  backend "s3" {
    bucket         = "tf-state-mycompany-98765"
    key            = "env/${terraform.workspace}/vpc.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-locks"
    encrypt        = true
  }
}
provider "aws" { region = var.region }

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.5.0"
  name = "devops-${terraform.workspace}"
  cidr = "10.0.0.0/16"
  azs  = ["us-east-1a","us-east-1b"]
  public_subnets  = ["10.0.1.0/24","10.0.2.0/24"]
  private_subnets = ["10.0.101.0/24","10.0.102.0/24"]
  enable_nat_gateway = true
}
full workflow
$ terraform init
$ terraform workspace new dev
$ terraform plan -var="region=us-east-1"
$ terraform apply -auto-approve
$ terraform workspace new prod
$ terraform workspace select dev
$ # Import an existing SG
$ terraform import aws_security_group.existing sg-0123456789abcdef0
  • Install Terraform and configure AWS credentials
  • Create VPC + public/private subnets using official module
  • Add security group + outputs; run plan & apply
  • Create and switch between dev and prod workspaces
  • Import an existing AWS resource and reconcile
  • Use LocalStack or Instruqt for free practice

Real-World Project 05.4

Single EC2 + RDS (free tier eligible)

Minimal VPC, security groups, one t2.micro + Postgres db.t3.micro. All defined in root module.

Production VPC + EKS cluster + RDS + ALB via modules

Separate environments via workspaces + tfvars. Reusable networking module. EKS managed node groups.

Multi-account landing zone with AWS Organizations, Control Tower baseline, SCPs, centralized logging, Transit Gateway

Troubleshooting 05.5

State lock stuck
terraform force-unlock <LOCK_ID>

Only run when you are sure no other apply is running.

Resource drift detected

Run terraform refresh then plan. Or use terraform apply -refresh-only.

Provider version or circular dependency errors

Pin exact provider versions. Break cycles by splitting modules or using -target for emergency fixes.

30-Day Roadmap 05.6

WEEK 1
Core HCL + Workflow
  • Resources, data sources, variables
  • plan / apply / destroy cycle
  • State inspection commands
WEEK 2
Modules & Composition
  • Writing and publishing modules
  • Registry modules
  • Version constraints
WEEK 3
State & Backends
  • Remote S3 + DynamoDB
  • Workspaces deep dive
  • Import, taint, moved
WEEK 4
AWS Production Patterns
  • EKS + RDS modules
  • Multi-env tfvars files
  • CI drift detection

Deep Dive: Advanced State & Module Patterns 05.7

State Migration Strategies

Use terraform state mv, terraform state rm, and moved blocks in 1.1+. Always backup state before migrations. For large refactors split state files using terraform workspace or separate root modules.

Module Best Practices

Keep modules small and focused. Expose only necessary inputs and outputs. Version modules strictly. Use semantic versioning. Test modules with terraform test (1.6+).

Sensitive input: redaction is not encryption

Local exercise, dummy input only. Assumptions: Terraform 1.9.8–1.12.1, WSL2 Ubuntu with Bash and jq 1.6+. The built-in terraform_data resource demonstrates persistence without a database, provider, credentials or network. Save the two snippets in a fresh private directory. Never use a real password here.

sensitive = true redacts normal plan/apply output; it does not remove the value from state or saved plans. Local state stores it in plain text. An encrypted S3 object decrypts to the same plaintext state when an authorized reader downloads it. Environment input avoids history and committed tfvars, but is still visible to suitably privileged processes. Disable shell tracing; do not run env, printenv, terraform output -raw, or terraform show -json in logs.

sensitive.tf
terraform {
  required_version = ">= 1.9.8, < 1.13.0"
}
variable "db_password" {
  type      = string
  sensitive = true
  validation {
    condition     = length(var.db_password) >= 12
    error_message = "Use at least 12 characters for this dummy exercise."
  }
}
# Built-in resource: no provider download, database or cloud account.
resource "terraform_data" "demo" {
  input = var.db_password
}
output "db_password" {
  value     = terraform_data.demo.output
  sensitive = true
}
sensitive-input.sh
# Bash in a NEW private directory; save sensitive.tf above here.
# Terraform 1.9.8 or 1.12.1; jq 1.6+ already installed. Dummy value only.
set -euo pipefail
set +x
umask 077
trap 'unset TF_VAR_db_password' EXIT
export CHECKPOINT_DISABLE=1  # Disable Terraform version-check network requests.
read -r -s -p 'Enter a dummy password (12+ characters): ' TF_VAR_db_password
printf '\n'
export TF_VAR_db_password
terraform init -backend=false
terraform validate
terraform plan -out=demo.plan > /dev/null
terraform apply demo.plan > /dev/null
# Check state exposure without displaying the value (exit 0 means found).
terraform state pull | jq -e '
  any(.resources[]; .type == "terraform_data" and
    .instances[0].attributes.input.value == env.TF_VAR_db_password)
' > /dev/null
# Output command and show -json can reveal secrets; do not print them.
unset TF_VAR_db_password

Verify and recover: the jq assertion checks equality without printing the value; a nonzero exit needs investigation of the resource address and input. If validation fails, unset the variable, supply another dummy value and rerun. Afterward discard this exercise’s demo.plan, terraform.tfstate and any backup; keep them out of Git and CI artifacts. Deleting a current state does not delete old bucket versions. A real leak requires secret rotation and auditing state readers and historical versions.

Production design exercise: S3 backend access boundary

Design only; do not apply. Terraform 1.9.8 S3 backend assumes an existing bucket, DynamoDB lock table and customer-managed KMS key. Substitute the illustrative bucket, account and role before review. This deny-only policy restricts readers even if another policy grants access; it does not grant the execution role permissions, and excludes other administrators from these objects.

state-bucket-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyNonTLS",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::example-tf-state",
        "arn:aws:s3:::example-tf-state/*"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    },
    {
      "Sid": "DenyOtherStateReaders",
      "Effect": "Deny",
      "Principal": "*",
      "Action": [
        "s3:GetObject",
        "s3:GetObjectVersion"
      ],
      "Resource": "arn:aws:s3:::example-tf-state/prod/db/*",
      "Condition": {
        "ArnNotEquals": {
          "aws:PrincipalArn": "arn:aws:iam::123456789012:role/TerraformState"
        }
      }
    }
  ]
}

Grant the dedicated execution role only s3:ListBucket for the relevant prefix and s3:GetObject/s3:PutObject for its state key; DynamoDB locking needs GetItem, PutItem, DeleteItem and DescribeTable on the lock table. Set backend encrypt = true and kms_key_id to the reviewed key ARN for SSE-KMS. The KMS key policy and IAM permissions must authorize that role for kms:Encrypt, kms:Decrypt and kms:GenerateDataKey; S3 access alone is insufficient. Enable S3 Block Public Access, versioning, audit logs and TLS enforcement with aws:SecureTransport. Isolate database state from networking state and review separate reader roles.

Verify in an authorized staging account later: permitted role can read/write and lock; unrelated role and non-TLS request are denied; a role without KMS access cannot decrypt. For AccessDenied inspect bucket/IAM policy, key policy, prefix and lock-table permissions; do not widen access to wildcard principals. Version restoration needs a reviewed backup and a fresh plan. Live KMS, rotation and backend tests remain unvalidated.

Official references: Terraform variables and environment inputs, sensitive state, terraform_data, S3 backend (1.9.8 assumptions; native S3 lockfiles require 1.10+, not this example), S3 permissions and SSE-KMS permissions (AWS current service documentation).

Runnable deletion guard: Conftest and synthetic plans

Offline synthetic exercise, not a recorded cloud plan. Prerequisites: Conftest v0.56.0 (embeds OPA 0.69.0), Bash and a fresh directory. import rego.v1 enables the v1 syntax on this version. Fixtures contain only the Terraform 1.9.8 JSON format 1.2 fields consumed by this policy; they are not full plans and cannot be applied. Save each named file and create the policy directory first.

policy/deny_db_delete.rego
package main
import rego.v1

deny contains msg if {
  some rc in input.resource_changes
  rc.type == "aws_db_instance"
  some action in rc.change.actions
  action == "delete"
  msg := sprintf("Database deletion blocked: %s", [rc.address])
}
tfplan-deny.json
{
  "format_version": "1.2",
  "terraform_version": "1.9.8",
  "resource_changes": [
    {
      "address": "aws_db_instance.payments_rds",
      "mode": "managed",
      "type": "aws_db_instance",
      "name": "payments_rds",
      "change": {
        "actions": [
          "delete"
        ],
        "before": {},
        "after": {}
      }
    }
  ]
}
tfplan-allow.json
{
  "format_version": "1.2",
  "terraform_version": "1.9.8",
  "resource_changes": [
    {
      "address": "aws_db_instance.payments_rds",
      "mode": "managed",
      "type": "aws_db_instance",
      "name": "payments_rds",
      "change": {
        "actions": [
          "update"
        ],
        "before": {},
        "after": {}
      }
    }
  ]
}
policy/deny_db_delete_test.rego
package main
import rego.v1

test_deny_db_delete if {
  violations := deny with input as {"resource_changes": [{"address": "aws_db_instance.payments_rds", "type": "aws_db_instance", "change": {"actions": ["delete"]}}]}
  violations == {"Database deletion blocked: aws_db_instance.payments_rds"}
}
test_allow_db_update if {
  violations := deny with input as {"resource_changes": [{"address": "aws_db_instance.payments_rds", "type": "aws_db_instance", "change": {"actions": ["update"]}}]}
  count(violations) == 0
}
test_deny_replacement if {
  violations := deny with input as {"resource_changes": [{"address": "aws_db_instance.payments_rds", "type": "aws_db_instance", "change": {"actions": ["create", "delete"]}}]}
  count(violations) == 1
}
test_allow_other_type if {
  violations := deny with input as {"resource_changes": [{"address": "aws_s3_bucket.logs", "type": "aws_s3_bucket", "change": {"actions": ["delete"]}}]}
  count(violations) == 0
}
verify-policy.sh
# Save the policy and fixtures above in a new exercise directory.
set -eu
conftest verify --policy policy
conftest test tfplan-allow.json --policy policy/deny_db_delete.rego
# Assert denial, while distinguishing policy errors from violations.
if conftest test tfplan-deny.json --policy policy/deny_db_delete.rego > deny.log 2>&1; then
  echo 'ERROR: deletion was allowed' >&2
  exit 1
else
  status=$?
  test "$status" -eq 1
  grep -F 'Database deletion blocked: aws_db_instance.payments_rds' deny.log
fi

Expected assertions (synthetic): verification passes all four unit tests, update exits 0, delete exits 1 and names the blocked database. A replacement also includes delete, even in create-before-destroy order. The other-type test documents scope: this policy only protects aws_db_instance, not every database service. Missing or malformed plan fields need a separate schema/plan-artifact check; do not treat an empty resource_changes array as proof of a safe production plan.

CI integration and recovery: for an already authorized plan stage use terraform plan -out=tfplan.binary, then terraform show -json tfplan.binary > tfplan.json and conftest test tfplan.json --policy policy/deny_db_delete.rego before approval/apply. Keep JSON private because it can reveal sensitive values. Apply that exact approved saved plan; replanning after the gate would bypass this check. Do not run cloud planning in this offline exercise. If the synthetic deny passes, check package main, --policy path and actions arrays. If compilation fails, confirm version and import. For a real blocked replacement, redesign the migration and obtain backup/restore review rather than deleting the policy. Live CI and other cloud resource coverage remain uncaptured.

Official references: Conftest usage and verify, Conftest v0.56.0 / OPA dependency, OPA 0.69.0 Rego language, OPA policy tests, Terraform JSON format and replacement actions (Terraform 1.9.8).

 Real Incident: terraform destroy on Production RDS

What happened: A DevOps engineer ran terraform destroy in the wrong terminal window — they were targeting a dev environment but had AWS_PROFILE=production in their shell. The production RDS PostgreSQL (16TB, payments data) began deleting.

# The fateful command
prod-term $ terraform destroy -target=aws_db_instance.payments_rds -auto-approve
aws_db_instance.payments_rds: Destroying... [id=payments-prod-postgres-15]
aws_db_instance.payments_rds: Still destroying... [30s elapsed]
← 11 minutes before DBA noticed via CloudWatch alarm

# Recovery: restore from automated snapshot (RDS 7-day retention saved us)
$ aws rds restore-db-instance-from-db-snapshot \
  --db-instance-identifier payments-prod-restored \
  --db-snapshot-identifier rds:payments-prod-postgres-15-2024-03-15-02-00

Prevention pattern:

main.tf — deletion_protection
# ALWAYS set deletion_protection on production databases
resource "aws_db_instance" "payments_rds" {
  # ...
  deletion_protection = true    # terraform destroy will FAIL with this set
  final_snapshot_identifier = "payments-rds-final-${formatdate("YYYY-MM-DD", timestamp())}"
  backup_retention_period = 30  # 30-day backup retention
  skip_final_snapshot = false   # Always take final snapshot
}

# Also: use lifecycle prevent_destroy for critical resources
resource "aws_db_instance" "payments_rds" {
  lifecycle {
    prevent_destroy = true  # Terraform plan will error before reaching API
  }
}

# Enforce before apply with the runnable Conftest policy above.

Terragrunt: DRY Multi-Environment IaC 05.8

Terragrunt wraps Terraform to eliminate code duplication across environments. Instead of copying the same backend.tf and provider.tf into every environment directory, define them once in a root root.hcl and inherit everywhere.

Repository layout
infrastructure/
├── root.hcl                    # Shared backend + provider config
├── modules/
│   ├── eks/                    # Reusable EKS module
│   ├── rds/                    # Reusable RDS module
│   └── vpc/                    # Reusable VPC module
└── environments/
    ├── dev/
    │   ├── vpc/terragrunt.hcl
    │   ├── eks/terragrunt.hcl
    │   └── rds/terragrunt.hcl
    ├── staging/
    │   └── ... (same structure)
    └── prod/
        ├── vpc/terragrunt.hcl
        ├── eks/terragrunt.hcl
        └── rds/terragrunt.hcl
root.hcl (defined once, inherited everywhere)
locals {
  account_vars = read_terragrunt_config(find_in_parent_folders("account.hcl"))
  env_vars     = read_terragrunt_config(find_in_parent_folders("env.hcl"))
  account_id   = local.account_vars.locals.account_id
  environment  = local.env_vars.locals.environment
  aws_region   = local.env_vars.locals.aws_region
}

generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = <<EOF
provider "aws" {
  region = "${local.aws_region}"
  assume_role {
    role_arn = "arn:aws:iam::${local.account_id}:role/TerraformRole"
  }
  default_tags {
    tags = {
      Environment = "${local.environment}"
      ManagedBy   = "terraform"
      Repository  = "infrastructure"
    }
  }
}
EOF
}

remote_state {
  backend = "s3"
  config = {
    bucket         = "tf-state-${local.account_id}-${local.aws_region}"
    key            = "${path_relative_to_include()}/terraform.tfstate"
    region         = local.aws_region
    encrypt        = true
    dynamodb_table = "terraform-state-locks"
  }
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }
}
environments/prod/eks/terragrunt.hcl
# Each environment module is just a thin config
include "root" {
  path = find_in_parent_folders()
}

terraform {
  source = "../../../modules//eks"  # double-slash = module root
}

inputs = {
  cluster_name    = "prod-eks-us-east-1"
  cluster_version = "1.29"
  vpc_id          = dependency.vpc.outputs.vpc_id
  subnet_ids      = dependency.vpc.outputs.private_subnet_ids
  node_groups = {
    general = {
      instance_types = ["m5.xlarge"]
      min_size       = 3
      max_size       = 20
      desired_size   = 5
    }
  }
}

dependency "vpc" {
  config_path = "../vpc"
  mock_outputs = {   # Allows plan without vpc deployed yet
    vpc_id            = "vpc-fake123"
    private_subnet_ids = ["subnet-fake1", "subnet-fake2"]
  }
}

Atlantis + CI Drift Detection 05.9

Atlantis: Pull Request Automation

Atlantis runs terraform plan on every PR and comments the diff. Only applies after PR approval. No human needs terminal access to production infra.

# In your PR, comment one of:
atlantis plan   ← runs terraform plan, posts diff
atlantis apply  ← applies after approval
atlantis unlock ← releases state lock

Drift Detection in CI

.github/workflows/drift-detect.yml
name: Terraform Drift Detection
on:
  schedule:
    - cron: '0 6 * * *'  # Daily at 6am
jobs:
  drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - name: Configure AWS
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456:role/TerraformReadOnly
          aws-region: us-east-1
      - name: Detect drift
        run: |
          terraform init
          if ! terraform plan -detailed-exitcode -out=drift.tfplan 2>&1; then
            echo "DRIFT DETECTED" | \
            curl -s -X POST $SLACK_WEBHOOK \
              -d '{"text":"🚨 Terraform drift detected in prod!"}'
          fi

Infracost CI: compare a baseline, then enforce a budget

Configuration example; no live API call or GitHub CI run. Assumptions: Infracost v0.10.39, setup action v3, checkout/setup-node v4, Node 20+, Ubuntu 24.04 runner and Terraform 1.9.8-compatible HCL in infra/ on both branches. Install the gate below into the base branch first. This workflow parses HCL directly; it does not run Terraform, providers or AWS APIs. Private modules and required variables need separately reviewed access/configuration. Fork PRs are skipped because secrets are unavailable; require a separate reviewed estimate before merge and make the budget job a required branch check for supported PRs.

.github/workflows/infracost.yml
name: Infracost budget
on:
  pull_request:
    paths: ['infra/**', 'scripts/infracost-budget.mjs', '.github/workflows/infracost.yml']
permissions:
  contents: read
jobs:
  budget:
    if: github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.base.sha }}
          path: base
          persist-credentials: false
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          path: proposed
          persist-credentials: false
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - uses: infracost/actions/setup@v3
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}
          version: '0.10.39'
          currency: USD
          enable-dashboard: 'false'
      - name: Estimate baseline and proposed HCL
        shell: bash
        run: |
          set -euo pipefail
          infracost breakdown --path=base/infra --format=json --out-file=baseline.json
          infracost diff --path=proposed/infra --compare-to=baseline.json --format=json --out-file=diff.json
      - name: Enforce USD 200 monthly increase limit
        # Run reviewed base-branch gate; the PR cannot weaken its threshold.
        run: node base/scripts/infracost-budget.mjs diff.json
scripts/infracost-budget.mjs
import { readFileSync } from 'node:fs';
try {
  const report = JSON.parse(readFileSync(process.argv[2], 'utf8'));
  if (report.currency !== 'USD' || !Array.isArray(report.projects) || !report.projects.length) throw new Error('Require a nonempty USD report');
  const cost = key => {
    const value = report[key];
    if (typeof value !== 'string' || !/^-?\d+(\.\d+)?$/.test(value)) throw new Error('Missing or invalid ' + key);
    const amount = Number(value);
    if (!Number.isFinite(amount)) throw new Error('Nonfinite ' + key);
    return amount;
  };
  const baseline = cost('pastTotalMonthlyCost');
  const proposed = cost('totalMonthlyCost');
  const delta = cost('diffTotalMonthlyCost');
  if (baseline < 0 || proposed < 0 || Math.abs(proposed - baseline - delta) > 0.01) throw new Error('Inconsistent cost totals');
  if (delta > 200) {
    console.error('BLOCK: monthly increase exceeds USD 200');
    process.exitCode = 1;
  } else console.log('PASS: monthly increase is within USD 200');
} catch (error) {
  console.error('BLOCK: ' + error.message);
  process.exitCode = 1;
}

The workflow compares exact base/head SHAs and uses the trusted base-branch gate so a PR cannot silently raise its threshold. Do not change this to pull_request_target or run PR scripts with secrets. Restrict secret-bearing jobs to reviewed contributors and pin action commit SHAs under your repository policy.

Offline simulated budget exercise

These numbers are invented for arithmetic practice, not AWS quotes or recorded estimates. Save the report fixtures and gate script; Node alone runs this offline test.

Simulated USD monthly estimates: the threshold limits increase, not total spend
ScenarioBaselineIncreaseProposed totalExpected gate
PR 42: larger database and IOPS$320.00+$462.50$782.50Block, exit 1
PR 43: right-sized database$320.00+$84.20$404.20Pass, exit 0
Boundary$320.00+$200.00$520.00Pass, exit 0
cost-fail.json
{
  "version": "0.2",
  "currency": "USD",
  "projects": [
    {
      "name": "synthetic-database"
    }
  ],
  "pastTotalMonthlyCost": "320.00",
  "totalMonthlyCost": "782.50",
  "diffTotalMonthlyCost": "462.50"
}
cost-pass.json
{
  "version": "0.2",
  "currency": "USD",
  "projects": [
    {
      "name": "synthetic-database"
    }
  ],
  "pastTotalMonthlyCost": "320.00",
  "totalMonthlyCost": "404.20",
  "diffTotalMonthlyCost": "84.20"
}
verify-budget.sh
set -eu
node scripts/infracost-budget.mjs cost-pass.json
if node scripts/infracost-budget.mjs cost-fail.json; then
  echo 'ERROR: over-budget report passed' >&2
  exit 1
else
  test "$?" -eq 1
fi

Verification and recovery: the gate rejects missing/null/nonnumeric costs, currency mismatches, empty projects and inconsistent totals. Test $200 (pass), $200.01 (block), a reduction (pass) and missing diff (block). On failed estimates check CLI status, API authorization and required variables; never replace null with zero. Right-size a blocked change or obtain a reviewed policy change. Review unsupported/skipped resources, unknown quantities, usage assumptions and migration costs separately: a passing net monthly delta does not guarantee a complete bill.

External prerequisite: INFRACOST_API_KEY in GitHub repository secrets is required for the Cloud Pricing API, even without a deployment. Never paste it in HCL or logs. API calls and PR comment integration were not run here; live validation requires externally authorized credentials. Plan-based alternative in an already authorized CI stage: terraform plan -out=tfplan.binary, terraform show -json tfplan.binary > tfplan.json, then infracost diff --path=tfplan.json --format=json --out-file=diff.json (uses prior state in the plan). Protect both plan files as secret-bearing artifacts. No plan or pricing request is part of the offline fixture exercise.

Official references: Infracost CLI inputs and diff, baseline comparison flag, v0.10.39 release, setup action v3 inputs, optional project configuration, GitHub Actions PR/secret security (v4 checkout, v3 Infracost action assumptions).

  • Set up Terragrunt with root.hcl, create dev and prod environment configs sharing same VPC module
  • Add deletion_protection = true and prevent_destroy lifecycle to a production RDS resource
  • Write OPA/Conftest policy that blocks any Terraform plan that would delete a database resource
  • Configure drift detection workflow that runs daily and sends Slack alert on changes
  • Integrate Infracost into CI pipeline — block PRs that increase monthly cost by >$200
  • Predict the Result: Plan and Exit Codes 05.10

    Recorded from a real run of scripts/recordings/terraform.sh; every output below is pasted from scripts/recordings/terraform.out. Cover the output, predict it, then compare.

    Environment: hashicorp/terraform:1.9.8 container with the hashicorp/local 2.5.2 provider, so no cloud account is needed. The configuration writes one file, app.conf, from a replicas variable.

    main.tf
    terraform {
      required_providers {
        local = {
          source  = "hashicorp/local"
          version = "2.5.2"
        }
      }
    }
    
    variable "replicas" {
      type    = number
      default = 2
    }
    
    resource "local_file" "app_config" {
      filename = "${path.module}/app.conf"
      content  = "replicas=${var.replicas}\n"
    }
    recorded run
    # Before the first apply
    $ terraform plan -no-color | grep '^Plan'
    Plan: 1 to add, 0 to change, 0 to destroy.
    
    # Same plan, as a CI gate
    $ terraform plan -no-color -detailed-exitcode > /dev/null; echo "exit=$?"
    exit=2
    
    # After terraform apply
    $ terraform plan -no-color | grep -E '^(Plan|No changes)'
    No changes. Your infrastructure matches the configuration.
    
    # And its exit code
    $ terraform plan -no-color -detailed-exitcode > /dev/null; echo "exit=$?"
    exit=0
    
    # Change an argument that cannot be updated in place
    $ terraform plan -no-color -var replicas=3 | grep -E '^Plan|must be replaced'
      # local_file.app_config must be replaced
    Plan: 1 to add, 0 to change, 1 to destroy.
    
    # Someone edits app.conf by hand
    $ echo 'replicas=5' > app.conf && terraform plan -no-color | grep '^Plan'
    Plan: 1 to add, 0 to change, 0 to destroy.

    -detailed-exitcode returns 0 for no changes, 2 for pending changes and 1 for errors, which is what a scheduled drift check alerts on. local_file cannot update content in place, so a new value means destroy and create. A hand edit to the file makes Terraform plan to create it again: the provider no longer finds the content it wrote, so it treats the old resource as gone.

    Predict: results this lesson prints

    Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

    What result does the lesson show for this command?

    $ terraform destroy -target=aws_db_instance.payments_rds -auto-approve
    Show the lesson's result

    The lesson shows:

    aws_db_instance.payments_rds: Destroying... [id=payments-prod-postgres-15]
    aws_db_instance.payments_rds: Still destroying... [30s elapsed]
    ← 11 minutes before DBA noticed via CloudWatch alarm

    What result does the lesson show for this command?

    $ terraform plan -no-color | grep '^Plan'
    Show the lesson's result

    The lesson shows:

    Plan: 1 to add, 0 to change, 0 to destroy.

    What result does the lesson show for this command?

    $ terraform plan -no-color -detailed-exitcode > /dev/null; echo "exit=$?"
    Show the lesson's result

    The lesson shows:

    exit=2

    Practice: troubleshoot and decide

    Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

    Troubleshooting drill

    A hand-made hotfix meets the next plan

    Output recorded from a real run on Terraform v1.12.1, hashicorp/local provider ~> 2.5, local state; no cloud account needed. Nothing runs on your machine.

    Builds on Architecture & How It Works, Troubleshooting.

    Terraform manages app.conf through a local_file resource with max_connections = 100. During an incident, on-call raised it to 500 by editing the file by hand, and the incident ended. The next morning a pipeline runs a plan before an unrelated change.

    1. Step 1 of 3: Predict before you look: what does terraform plan propose for app.conf?

    Design decision

    Separate dev, staging and prod: workspaces or per-environment directories?

    Builds on Core Components & Concepts, Real-World Project.

    A team of six manages dev, staging and prod with Terraform from CI. The lesson's project separates environments with workspaces + tfvars; its Terragrunt section uses one directory per environment.

    Constraints

    • Prod lives in its own AWS account with its own credentials
    • Prod has resources dev does not (for example a read replica)
    • A mistaken apply against prod must be hard to do by accident
    • Three environments, one region, no plans to grow soon
    Which do you choose?

    Lab: simulated terminal, nothing runs on your machine

    Simulated nothing runs on your machine

    1. 1 Run the first command shown in the section “WSL Hands-On Lab”
    Run the first command shown in the section “WSL Hands-On Lab”

    Ready. Type the command for the current goal.

    Check yourself

    A Terraform change affects resources with dependencies. How does Terraform choose the changes and their execution order?

    Explanation

    In 'Architecture & How It Works', Terraform builds a DAG from configuration, compares configuration to state, calculates the minimal changes, and executes them in order. Recreating everything or ignoring state and dependencies contradicts this model.

    A local Terraform variable is marked sensitive = true. Can you safely treat the local state file as free of its value?

    Explanation

    In 'Sensitive input: redaction is not encryption', sensitive = true redacts normal plan/apply output but does not remove values from state or saved plans. Local state stores them in plain text; environment input does not change that.

    Infrastructure changed outside Terraform. You want to reconcile state without applying configuration changes to infrastructure. Which command fits?

    Explanation

    In 'Troubleshooting', 'Resource drift detected' recommends 'terraform refresh' then plan, or 'terraform apply -refresh-only'. Unlocking, removing a state entry, or initializing does not perform that refresh-only reconciliation.

    For the lesson's S3 backend example, you need state locking to coordinate concurrent operations. Which configured service provides the lock?

    Explanation

    In 'WSL Hands-On Lab', the S3 backend sets dynamodb_table = "tf-locks". 'Core Components & Concepts' pairs the S3 bucket with a DynamoDB table for remote state and locking; plugins, workspaces, and modules have other roles.

    Why does Terraform download providers during init?

    Providers translate HCL configuration into API calls for the infrastructure being managed.

    Space flips the current card.

    Capability coverage: L1, L2, L3 covered

    No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

    Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

    Skills by experience level for this lesson
    SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
    Understand Missing · 3 sections Not covered Not covered Not covered
    Operate Not covered Missing · 2 sections Not covered Not covered
    Troubleshoot Not covered Not covered Missing · 1 section Not covered
    Automate Not covered Missing · 2 sections Missing · 3 sections Not covered
    Secure Not covered Not covered Not covered Not covered
    Observe Not covered Not covered Not covered Not covered
    Design Not covered Not covered Missing · 1 section Not covered
    Make trade-offs Not covered Not covered Not covered Not covered

    How this lesson fits each role