Terraform Advanced — Meta-Arguments Exercises

less than 1 minute read

Practice meta-argument patterns.


Exercise 1 — Zero-Downtime Replacement

Task: Write an EC2 instance resource that creates the replacement before destroying the old one.

Answer
resource "aws_instance" "app" {
  ami           = var.ami_id
  instance_type = "t3.micro"

  lifecycle {
    create_before_destroy = true
  }
}

Exercise 2 — Ignore External Changes

Task: An ASG has desired_capacity managed by an auto-scaling policy. Write the lifecycle to ignore it.

Answer
resource "aws_autoscaling_group" "app" {
  desired_capacity = 2
  min_size         = 1
  max_size         = 10
  # ...

  lifecycle {
    ignore_changes = [desired_capacity]
  }
}

Exercise 3 — Precondition Validation

Task: Write a precondition that ensures var.environment is one of dev, staging, or prod.

Answer
resource "aws_vpc" "main" {
  cidr_block = var.cidr

  lifecycle {
    precondition {
      condition     = contains(["dev", "staging", "prod"], var.environment)
      error_message = "environment must be dev, staging, or prod"
    }
  }
}

Chapter Summary

  • count: on/off toggles only — never for lists that change
  • for_each: named collections — safe to add/remove items
  • lifecycle: create_before_destroy, prevent_destroy, ignore_changes
  • depends_on: only for invisible dependencies (IAM propagation, etc.)
  • replace_triggered_by: force recreation on external changes
  • preconditions/postconditions: validate before create, verify after

← Preconditions & Postconditions Chapter 8: Custom Providers →

Updated: