Terraform Advanced — Production Patterns Exercises

1 minute read

Practice production patterns.


Exercise 1 — Default Tags

Task: Configure the AWS provider to add Environment, Team, and ManagedBy tags to all resources.

Answer
provider "aws" {
  region = "us-east-1"
  default_tags {
    tags = {
      Environment = var.environment
      Team        = var.team
      ManagedBy   = "terraform"
    }
  }
}

Exercise 2 — Drift Detection Workflow

Task: Write a cron-based GitHub Actions workflow that runs terraform plan every morning and alerts on drift.

Answer
name: Drift Detection
on:
  schedule:
    - cron: '0 8 * * *'
jobs:
  drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - id: plan
        run: terraform plan -detailed-exitcode
        continue-on-error: true
      - if: steps.plan.outputs.exitcode == '2'
        run: echo "DRIFT DETECTED" && exit 1

Exercise 3 — terraform_data Trigger

Task: Write a terraform_data resource that runs a script whenever an EC2 instance is replaced.

Answer
resource "terraform_data" "post_deploy" {
  triggers_replace = [aws_instance.app.id]

  provisioner "local-exec" {
    command = "./scripts/post-deploy.sh ${aws_instance.app.public_ip}"
  }
}

Chapter Summary

  • Three-tier repos: modules, live configs, platform wrappers
  • Account-per-environment: blast-radius isolation with AWS Organizations
  • Zero-downtime: create_before_destroy, rolling updates, blue/green
  • Cost tagging: default_tags + tag validation + AWS Config rules
  • Drift detection: scheduled terraform plan with -detailed-exitcode
  • null_resource/terraform_data: escape hatch for unsupported operations

← null_resource Escape Hatch Chapter 16: Next Steps →

Updated: