Terraform Advanced — Remote State Exercises

1 minute read

Practice remote state management.


Exercise 1 — Bootstrap Backend

Task: Write the Terraform to create an S3 bucket with versioning, encryption, and a DynamoDB lock table.

Answer
resource "aws_s3_bucket" "state" {
  bucket = "my-tf-state-${data.aws_caller_identity.current.account_id}"
}

resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id
  versioning_configuration { status = "Enabled" }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    apply_server_side_encryption_by_default { sse_algorithm = "aws:kms" }
  }
}

resource "aws_dynamodb_table" "locks" {
  name         = "tf-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"
  attribute {
    name = "LockID"
    type = "S"
  }
}

data "aws_caller_identity" "current" {}

Exercise 2 — Cross-Stack Reference

Task: Stack A outputs vpc_id. Write the data source in Stack B to read it.

Answer
data "terraform_remote_state" "networking" {
  backend = "s3"
  config = {
    bucket = "my-tf-state-123456789012"
    key    = "prod/networking/terraform.tfstate"
    region = "us-east-1"
  }
}

locals {
  vpc_id = data.terraform_remote_state.networking.outputs.vpc_id
}

Exercise 3 — Force Unlock

Task: A colleague’s laptop crashed during terraform apply. The state is locked. How do you fix it?

Answer
# 1. Check the lock info
$ terraform plan
# Error: state lock with ID "abc-123-def"

# 2. Verify the lock holder isn't still running
# (Check with your colleague!)

# 3. Force unlock
$ terraform force-unlock abc-123-def

⚠️ Warning: Only force-unlock after confirming no one is running an apply. Unlocking during an active apply can corrupt state.


Chapter Summary

  • S3 + DynamoDB is the production standard for AWS state management
  • Always encrypt state — it contains secrets (use SSE-KMS for audit trails)
  • Partial backend config keeps credentials out of .tf files
  • terraform_remote_state reads outputs cross-stack (but creates coupling)
  • State isolation limits blast radius — one state per service per environment

← State Isolation Patterns Chapter 3: Workspaces vs Directories →

Updated: