Advanced
Searching inHow-to guides
How to search
  • Type the task in your own words (find port, open firewall, disk full) or paste an error message in quotes.
  • Choose "Quick answer" to see only the commands, or an area to stay in one field.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

How-to 48IaC · Terraform

How to store Terraform state in S3 with locking

Terraform remembers what it built in the state file. On a laptop that file is lost, can not be shared, and two people can run apply at the same time and break things. The team setup is a remote backend with locking: on AWS that is an S3 bucket. Since Terraform 1.10 S3 can lock by itself (use_lockfile), so the old DynamoDB lock table is no longer needed. This how-to creates a safe bucket, moves the state, and shows how locking and recovery work.

  • 5 Lessons
  • 3 Commands

$ run as a normal user# run as root (or with sudo)

48.1

The quick answer

backend.tf
terraform {
  required_version = ">= 1.10"
  backend "s3" {
    bucket       = "acme-tfstate-111122223333"
    key          = "shop/prod/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
  }
}
terraform init -migrate-state

48.2

Step by step

  1. Create the bucket once (by hand or in a small "bootstrap" Terraform project) — private, versioned, encrypted:
aws s3api create-bucket --bucket acme-tfstate-111122223333 --region eu-west-1 --create-bucket-configuration LocationConstraint=eu-west-1
aws s3api put-bucket-versioning --bucket acme-tfstate-111122223333 --versioning-configuration Status=Enabled
aws s3api put-public-access-block --bucket acme-tfstate-111122223333 --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-encryption --bucket acme-tfstate-111122223333 --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]}'

Versioning is your undo button: every state write keeps the old version.

  1. One key per project and environment — never one state for everything:
KeyHolds
network/prod/terraform.tfstateVPC, subnets of prod.
shop/prod/terraform.tfstateThe shop app in prod.
shop/dev/terraform.tfstateThe shop app in dev.
  1. Move the existing local state to S3:
terraform init -migrate-state
Do you want to copy existing state to the new backend? yes
Successfully configured the backend "s3"!
terraform state list | head
  1. How the lock works: during plan/apply Terraform writes shop/prod/terraform.tfstate.tflock next to the state. A second run waits or stops:
terraform apply -lock-timeout=5m
Error acquiring the state lock
Lock Info:
  ID:        7b3c1f0e-1a2b-4c3d-9e8f-0a1b2c3d4e5f
  Who:       alice@build-01
  1. The IAM rights the pipeline role needs (only on its own keys): s3:ListBucket on the bucket, and s3:GetObject, s3:PutObject, s3:DeleteObject on shop/prod/terraform.tfstate and shop/prod/terraform.tfstate.tflock, plus kms:Encrypt/kms:Decrypt on the key.
  2. Protect the state like a password store — it can contain secrets (database passwords, keys) in plain text: few people may read the bucket, CloudTrail on, no public access, no copy on laptops.

48.3

Check that it worked

aws s3 ls s3://acme-tfstate-111122223333/shop/prod/
terraform plan
No changes. Your infrastructure matches the configuration.

The state file is in S3, the local terraform.tfstate is no longer used (delete it after the check), and plan shows no changes.

48.4

Common problems

ProblemCauseFix
Error acquiring the state lockAnother run is busy — or a crashed run left the lock.Wait. Only if you are sure no run is active: terraform force-unlock LOCK_ID.
AccessDenied on the .tflock objectThe IAM policy allows only the state key.Add the .tflock key to the policy.
Backend configuration changedYou changed the backend block.terraform init -reconfigure (new place, no copy) or -migrate-state (copy).
Unsupported argument "use_lockfile"Terraform older than 1.10.Update Terraform (or keep the DynamoDB lock table on old versions).
Wrong state was overwrittenTwo projects used the same key.Restore the old version from S3 versioning; use unique keys.
Secrets visible in the stateTerraform stores resource attributes.Restrict bucket access; use ephemeral values / secret managers where you can.

48.5

Go further

1Since which Terraform version can the S3 backend lock without DynamoDB?

1.10 — with use_lockfile = true.

2Why turn on versioning on the state bucket?

Every state write keeps the old version, so a broken or overwritten state can be restored.

All commands in this chapter