Skip to content

Lesson 23 of 30Infrastructure as code

Terraform on AWS

The plan and apply workflow, HCL that scales, S3 state with native locking, modules, safe refactors, secrets in state, and Terraform in CI.

20 min read0/4 questions

Your first infrastructure pull request at a new job adds one tag to a database. The plan posted on the PR says 1 to add, 0 to change, 1 to destroy, and the line above it says must be replaced. If you approve that, you delete the production database. Reading Terraform plans, structuring code so small changes stay small, and keeping state safe are the everyday skills of anyone who touches AWS at a company that uses Terraform, which is a large share of them. This lesson builds them on a real example: the private S3 bucket and CloudFront distribution with OAC from the CloudFront lesson, written in HCL.

The workflow

Every Terraform change follows the same six commands. Learn what each one does, because CI runs exactly these.

terraform init                 # download providers and modules, configure the backendterraform fmt -recursive       # canonical formatting (CI uses fmt -check)terraform validate             # syntax and type checks, no AWS callsterraform plan -out=tfplan     # refresh state, diff, save the exact planterraform apply tfplan         # apply that saved plan and nothing elseterraform destroy              # plan and apply deleting everything in this state

Always apply a saved plan in automation. terraform apply on its own plans again, and if something changed between your review and the apply, you get a plan nobody read. Applying tfplan either does exactly what was reviewed or refuses because the state moved on.

Reading a plan

Terraform will perform the following actions:
 
  # aws_s3_bucket.site must be replaced
-/+ resource "aws_s3_bucket" "site" {
      ~ bucket = "shop-site-prod" -> "shop-web-prod" # forces replacement
      ~ id     = "shop-site-prod" -> (known after apply)
        # (8 unchanged attributes hidden)
    }
 
  # aws_sqs_queue.emails will be updated in-place
  ~ resource "aws_sqs_queue" "emails" {
      ~ visibility_timeout_seconds = 30 -> 60
        # (12 unchanged attributes hidden)
    }
 
Plan: 1 to add, 1 to change, 1 to destroy.
  • + create, - destroy, ~ update in place.
  • -/+ replace: destroy the old one, then create the new one. +/- is the same with the new one created first (create_before_destroy).
  • # forces replacement names the attribute that caused it. Bucket names, a DynamoDB table's key schema, an RDS instance's encryption setting and an EC2 instance's subnet all force replacement, because AWS cannot change them on a live resource.
  • (known after apply) is a value AWS will generate, such as an ARN or ID.

The habit: before approving, search the plan for must be replaced and destroy. Every one should be intentional.

HCL building blocks

A root module is just a folder of .tf files. Terraform reads them all together, so the split into files is for people.

versions.tf
terraform {
  required_version = ">= 1.11"
 
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
 
  backend "s3" {
    bucket       = "acme-tfstate-123456789012"
    key          = "prod/site/terraform.tfstate"
    region       = "eu-west-2"
    encrypt      = true
    use_lockfile = true
  }
}
 
provider "aws" {
  region = var.region
 
  default_tags {
    tags = {
      Project     = "shop"
      Environment = var.env
      ManagedBy   = "terraform"
    }
  }
}

~> 6.0 means "6.x, never 7.0": major provider versions contain breaking changes, so you upgrade them on purpose. terraform init records the exact versions and checksums it picked in .terraform.lock.hcl. Commit that file, like package-lock.json, so CI and every laptop use the same provider build. If teammates use different operating systems, run terraform providers lock with each -platform you need so the lock file has checksums for all of them. default_tags puts the same tags on every resource the provider creates, which makes cost reports and ownership questions easy.

variables.tf
variable "env" {
  type        = string
  description = "Deployment environment"
 
  validation {
    condition     = contains(["dev", "staging", "prod"], var.env)
    error_message = "env must be dev, staging or prod."
  }
}
 
variable "region" {
  type    = string
  default = "eu-west-2"
}
 
variable "price_classes" {
  type = map(string)
  default = {
    dev     = "PriceClass_100"
    staging = "PriceClass_100"
    prod    = "PriceClass_All"
  }
}

Variables are typed (string, number, bool, list(...), map(...), set(...), object({...})), and validation blocks fail the plan with a clear message instead of a confusing AWS error later. Mark a variable sensitive = true to hide it in plan output, remembering from the previous lesson that this does not keep it out of state. Locals name computed values, data sources read things Terraform does not manage (your account ID, a managed cache policy, an IAM policy document), and outputs expose values to people and other configurations.

The full example: S3, CloudFront and OAC

This is the same architecture the CloudFront lesson built by hand, as code: a private bucket, an Origin Access Control, a distribution, and a bucket policy that trusts only that distribution.

site.tf
data "aws_caller_identity" "current" {}
 
locals {
  bucket_name = "shop-site-${var.env}-${data.aws_caller_identity.current.account_id}"
}
 
resource "aws_s3_bucket" "site" {
  bucket = local.bucket_name
}
 
resource "aws_s3_bucket_public_access_block" "site" {
  bucket                  = aws_s3_bucket.site.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
 
resource "aws_cloudfront_origin_access_control" "site" {
  name                              = "shop-site-${var.env}"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}
 
data "aws_cloudfront_cache_policy" "optimized" {
  name = "Managed-CachingOptimized"
}
 
resource "aws_cloudfront_distribution" "site" {
  enabled             = true
  default_root_object = "index.html"
  price_class         = var.price_classes[var.env]
 
  origin {
    origin_id                = "site-bucket"
    domain_name              = aws_s3_bucket.site.bucket_regional_domain_name
    origin_access_control_id = aws_cloudfront_origin_access_control.site.id
  }
 
  default_cache_behavior {
    target_origin_id       = "site-bucket"
    viewer_protocol_policy = "redirect-to-https"
    allowed_methods        = ["GET", "HEAD"]
    cached_methods         = ["GET", "HEAD"]
    cache_policy_id        = data.aws_cloudfront_cache_policy.optimized.id
    compress               = true
  }
 
  custom_error_response {
    error_code         = 403
    response_code      = 200
    response_page_path = "/index.html"
  }
 
  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }
 
  viewer_certificate {
    cloudfront_default_certificate = true
  }
}
 
data "aws_iam_policy_document" "site" {
  statement {
    sid       = "AllowCloudFrontOAC"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.site.arn}/*"]
 
    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }
 
    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.site.arn]
    }
  }
}
 
resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
  policy = data.aws_iam_policy_document.site.json
}
 
output "site_url" {
  value = "https://${aws_cloudfront_distribution.site.domain_name}"
}

Notice what you never wrote: the order. Terraform builds a dependency graph from references. The bucket policy references the distribution's ARN, which references the OAC and the bucket, so Terraform creates bucket and OAC first (in parallel), then the distribution, then the policy. Using aws_iam_policy_document instead of a JSON string gets you validation and clean diffs. And in AWS provider v4 and later, bucket settings (public access block, policy, versioning, encryption) are separate resources, so changing one never rewrites the others.

count, for_each and the index-shifting bug

Both create many copies of a resource. The difference is how each copy is addressed in state, and that difference has deleted real production resources.

Pythoncount_vs_for_each.py
def by_count(names): return {f"aws_sqs_queue.jobs[{i}]": name for i, name in enumerate(names)} def by_for_each(names): return {f'aws_sqs_queue.jobs["{name}"]': name for name in names} def plan(before, after): for addr in sorted(before.keys() | after.keys()): old, new = before.get(addr), after.get(addr) if old == new: continue if old is None: print(f" + {addr:<30} create {new}") elif new is None: print(f" - {addr:<30} destroy {old}") else: print(f" -/+ {addr:<30} replace {old} -> {new} (queue name forces it)") old = ["orders", "emails", "refunds"]new = ["orders", "refunds"] # remove "emails" from the list print("count = length(var.queues):")plan(by_count(old), by_count(new))print("for_each = toset(var.queues):")plan(by_for_each(old), by_for_each(new))
Output
Press Run (⌘ Enter) to see what happens.

With count, the queues are jobs[0], jobs[1], jobs[2]. Remove the middle one and refunds slides from index 2 to index 1, so Terraform replaces jobs[1] and destroys jobs[2]. Any messages in those queues are gone. With for_each, each copy is keyed by a stable string, so removing emails touches only emails.

The rule: use for_each with a map or set of strings for anything that has an identity. Use count only for identical copies or as an on-off switch (count = var.enable_waf ? 1 : 0).

Predict the outputPython

What does this print?

names = ["api", "worker", "cron"]
names.insert(0, "web")

before = {i: n for i, n in enumerate(["api", "worker", "cron"])}
after = {i: n for i, n in enumerate(names)}
touched = [i for i in after if before.get(i) != after[i]]
print(len(touched))
Need a nudge? Hints walk you through it.

Dynamic blocks are the same idea for nested blocks inside one resource, such as one ingress block per port in a security group. Use them sparingly: a resource built entirely from dynamic blocks is hard to read in review.

Remote state in S3 with native locking

Local state on a laptop works for one person for one afternoon. Teams use a remote backend, and on AWS that is an S3 bucket.

  • Versioning on, so you can recover a corrupted or wrongly overwritten state.
  • Encryption with SSE-S3 or a KMS key, Block Public Access on, and IAM that lets only the CI roles (and a break-glass role) read it. Remember that state contains secrets.
  • Locking so two applies cannot run at once. Since Terraform 1.10 the S3 backend locks natively with use_lockfile = true: it writes a lock object next to the state (<key>.tflock) with a conditional write that fails if the lock already exists. The old approach, a DynamoDB table set with dynamodb_table, is deprecated and will be removed, so new configurations should not create one. When migrating, you can enable both for a while, then remove the DynamoDB setting.
  • One state per environment and component: prod/network, prod/site, dev/site. A small state plans quickly and has a small blast radius. A single giant state means every PR locks everything and every plan takes minutes.
Two engineers, one state, native S3 locking
Alice (CI run)S3 state bucketBob (CI run)PUT prod/site/terraform.tfstate.tflock (only if absent)200 OK, lock heldPUT ...tflock (only if absent)412 Precondition FailedPUT terraform.tfstate (new version)DELETE ...tflock

Before planning, Terraform creates the lock object with a conditional write. It succeeds because no lock exists.

1/6

If a run crashes while holding the lock, terraform force-unlock <LOCK_ID> removes it. Only do that once you are sure the other run is dead, or two applies will race on the same state.

The state bucket has a chicken-and-egg problem: you cannot store the state of the bucket that stores state. Most teams create it once with a tiny bootstrap configuration (local state, committed nowhere) or with a CloudFormation template, and never touch it again.

Sharing values between states

The network state creates the VPC, and the app state needs its ID. Two options:

  • data "terraform_remote_state" reads another state's outputs directly. Simple, but the reader needs read access to the whole state file, secrets included.
  • Publish the value to SSM Parameter Store (aws_ssm_parameter in the producer, data "aws_ssm_parameter" in the consumer). The consumer needs only ssm:GetParameter on one path, and CDK or scripts can read it too. Most security reviews prefer this.
A Terraform repo with modules and per-environment states
  • infra/
  • modules/
  • static-site/bucket, OAC, distribution, policy
  • main.tf
  • variables.tf
  • outputs.tf
  • live/
  • dev/
  • network/
  • main.tfbackend key dev/network
  • site/
  • main.tfcalls ../../../modules/static-site
  • terraform.tfvarsenv = "dev"
  • prod/
  • network/
  • main.tfbackend key prod/network
  • site/
  • main.tf
  • terraform.tfvarsenv = "prod"
  • .tflint.hcl
  • .terraform.lock.hcl

Modules

A module is any folder of .tf files with variables in and outputs out. Calling it looks like a resource:

live/prod/network/main.tf
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 6.0"
 
  name = "shop-prod"
  cidr = "10.0.0.0/16"
 
  azs             = ["eu-west-2a", "eu-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
 
  enable_nat_gateway = true
  single_nat_gateway = true
}
 
resource "aws_ssm_parameter" "vpc_id" {
  name  = "/shop/prod/network/vpc-id"
  type  = "String"
  value = module.vpc.vpc_id
}

The community terraform-aws-modules collection (vpc, eks, rds, lambda and more) is widely used and saves weeks. Always pin version, read the module's changelog before bumping a major, and read the plan: a module upgrade can rename internal resources.

Write your own module when the same group of resources appears three or more times with a clear interface, like static-site. Do not wrap a single resource in a module that just passes every argument through: it adds a layer to debug and saves nothing. Internal modules are usually versioned with git tags (source = "git::https://github.com/acme/infra-modules.git//static-site?ref=v1.4.0") or a private registry.

Refactoring without destroying anything

Code changes shape over time. Terraform has blocks that tell it "this is the same resource, just moved", so a refactor plans as zero changes.

refactors.tf
# Renamed a resource or moved it into a module: same real bucket.
moved {
  from = aws_s3_bucket.assets
  to   = aws_s3_bucket.static_assets
}
 
# Adopt a bucket someone created by hand.
import {
  to = aws_s3_bucket.legacy_uploads
  id = "shop-legacy-uploads"
}
 
# Stop managing a bucket without deleting it.
removed {
  from = aws_s3_bucket.old_reports
 
  lifecycle {
    destroy = false
  }
}

moved updates the address in state on the next apply. import blocks are planned and reviewed like any change (the old terraform import command changed state immediately with no review). If you do not want to write the resource block by hand, terraform plan -generate-config-out=generated.tf drafts it from the real resource; clean it up before committing. removed with destroy = false forgets a resource but leaves it running, for example when moving it to another state.

The lifecycle block controls how Terraform treats a resource:

  • prevent_destroy = true makes any plan that would destroy it fail. Put it on databases and state buckets.
  • create_before_destroy = true creates the replacement first, then deletes the old one, for things like launch templates and certificates where a gap means downtime. It needs a name that can coexist with the old one (name_prefix instead of name).
  • ignore_changes = [desired_capacity] tells Terraform to stop fighting a value something else manages, such as an autoscaler.

Keeping secrets out of state

Since every attribute lands in state, a generated database password does too. You have three ways to avoid it, from best to most manual.

  1. Let AWS own the secret. manage_master_user_password = true on aws_db_instance makes RDS generate the password and store it in Secrets Manager. Terraform never sees it.
  2. Write-only arguments (Terraform 1.11+). Arguments ending in _wo, such as password_wo on aws_db_instance and secret_string_wo on aws_secretsmanager_secret_version, are sent to AWS and never stored in plan or state. They pair with ephemeral resources (1.10+), which produce values that exist only during a run.
  3. Create the secret outside Terraform and pass only its ARN in.
secrets.tf
ephemeral "random_password" "db" {
  length  = 32
  special = false
}
 
resource "aws_secretsmanager_secret_version" "db" {
  secret_id                = aws_secretsmanager_secret.db.id
  secret_string_wo         = ephemeral.random_password.db.result
  secret_string_wo_version = 1
}

Because Terraform cannot see a write-only value, it cannot diff it. You bump the matching _version number when you want to send a new value. Provider support for _wo arguments grows with each release, so check the resource's documentation.

Terraform in CI

Nobody should run apply against production from a laptop. The standard shape:

  • On pull request: fmt -check, validate, tflint, a policy scan, then plan using a read-only OIDC role for that environment. Post the plan (or its summary) as a PR comment so reviewers read it next to the code.
  • On merge to main: plan again against the current state, save tfplan, and apply it with an apply role. Gate production behind a GitHub environment with required reviewers.
  • Nightly: terraform plan -detailed-exitcode on each state. Exit code 2 means "changes present", which on an untouched main branch means drift. Alert on it.

Short-lived credentials come from the same GitHub OIDC trust you saw in Deploying a Full-Stack App, with one role per environment and the plan role unable to write anything. Tools such as Atlantis (self-hosted, runs plans from PR comments) and HCP Terraform (HashiCorp's hosted runs, state and policies) package this workflow if you would rather not build it in Actions. CI/CD to AWS with GitHub Actions covers the pipeline itself.

Put it in order5 steps

Order the steps of a safe production Terraform change.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each situation to the Terraform feature that handles it.

Choose an item, then its match on the other side.
Quick check
You are writing a new Terraform configuration with an S3 backend on Terraform 1.11. How should state locking be configured?
Need a nudge? A hint rules out a wrong answer.
Key terms
.terraform.lock.hcl
The committed file recording exact provider versions and checksums chosen by terraform init.
forces replacement
A plan note meaning the changed attribute cannot be updated in place, so the resource is destroyed and recreated.
use_lockfile
The S3 backend setting (Terraform 1.10+) that locks state with a .tflock object instead of DynamoDB.
for_each
Creates one instance per map or set key, addressed by that key, so removing one item does not shift the others.
moved block
Tells Terraform a resource changed address, so a rename or module move plans as no change.
write-only argument
An argument such as password_wo that is sent to the provider but never stored in plan or state (Terraform 1.11+).
detailed exit code
plan -detailed-exitcode returns 2 when changes exist, which CI uses to detect drift.