Terraform Tutorial — Backends Practice Exercises

1 minute read

Practice configuring and migrating Terraform backends.


Exercise 1: S3 Backend

Task: Write a complete backend "s3" block that stores state in bucket acme-tf-state, key prod/web-app/terraform.tfstate, region us-east-1, with encryption and DynamoDB locking using table tf-locks.

Answer
terraform {
  backend "s3" {
    bucket         = "acme-tf-state"
    key            = "prod/web-app/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "tf-locks"
  }
}

Exercise 2: Migration

Task: You have state stored locally and want to move it to S3. What are the exact steps?

Answer
  1. Add the backend "s3" block to your configuration
  2. Run terraform init -migrate-state
  3. Confirm the migration when prompted (yes)
  4. Verify with terraform state list
  5. Delete the local terraform.tfstate file (it’s now in S3)

Exercise 3: .gitignore

Task: List five file patterns that should always be in a Terraform project’s .gitignore.

Answer
  1. *.tfstate — state files contain secrets
  2. *.tfstate.* — state backup files
  3. .terraform/ — provider plugins (large, regenerated)
  4. *.tfvars — may contain sensitive variable values
  5. crash.log — Terraform crash logs with sensitive info

Exercise 4: Backend Comparison

Task: Compare S3 backend with Terraform Cloud. When would you choose each?

Answer

Choose S3 backend when:

  • Your team is AWS-only
  • You want simple setup with existing AWS infrastructure
  • You manage access through IAM policies

Choose Terraform Cloud when:

  • You need a UI for state management and history
  • You want built-in policy enforcement (Sentinel)
  • You need remote execution (runs happen in the cloud, not on developer machines)
  • Your team works across multiple cloud providers

Chapter Summary

In this chapter, you learned:

  • Local backend: simple but single-user, no encryption, no locking
  • S3 backend: team-friendly with encryption, versioning, and DynamoDB locking
  • DynamoDB: provides state locking to prevent concurrent modifications
  • Terraform Cloud: managed backend with UI, policies, remote runs
  • Migration: terraform init -migrate-state copies state between backends
  • .gitignore: always exclude *.tfstate, .terraform/, *.tfvars, crash.log

Next up: Troubleshooting — debugging common Terraform errors.


← Backend Migration and .gitignore Troubleshooting →