Terraform Labs · Lab 6 of 9
AWS: Remote State in S3 with Locking
Bootstrap a hardened S3 bucket for Terraform state (versioning, KMS encryption, public access blocked, TLS only, protected from deletion), then move an existing configuration's local state into it with S3-native locking.
- Environment
- AWS
- Level
- Intermediate
- Time
- About 45 min
- Cost
- Well under $0.01: a few small state files and requests in S3
You will build
A state bucket you could use at work, and a configuration whose state lives in it — shared, locked against concurrent runs and versioned so any bad write can be rolled back.
Before you start
- Lab: AWS: A Web Server in Its Own VPC
Terraform 1.10 or newer (for use_lockfile)
AWS CLI signed in
Local state works for one person on one laptop. As soon as a teammate or a CI pipeline runs Terraform, state must live in one shared place with locking. The bucket itself is created by a small bootstrap configuration, because a configuration can't store its state in a bucket it hasn't created yet.
Before and after
With local state, terraform.tfstate exists only on your laptop: teammates and CI can't see it, and
losing the laptop loses track of everything. With the S3 backend, everyone reads and writes one object
(shop/dev/app.tfstate), and a lock file (app.tfstate.tflock) exists only while someone is applying.
Two configurations
bootstrap/ runs once and creates the bucket; its own small state stays local. The bucket is protected by
versioning (every state write kept), SSE-KMS encryption, a full public access block, a
TLS-only bucket policy and prevent_destroy. app/ declares backend "s3" and moves its existing
local state into the bucket with terraform init -migrate-state.
Project structure
tf-state/
├── .gitignore
├── bootstrap/
│ └── main.tf # the state bucket (run once per account)
└── app/
├── main.tf # any configuration; here one SSM parameter
└── backend.tf # added in step 6
Steps
-
1The bootstrap configuration
Everything about this bucket protects the state: versioning keeps every revision, encryption and a TLS-only policy protect it, public access is blocked, and
prevent_destroystops an accidentalterraform destroy.bootstrap/main.tf terraform { required_version = ">= 1.10" # use_lockfile needs 1.10+ required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } provider "aws" { region = var.region } variable "region" { type = string default = "us-east-1" } variable "state_bucket_name" { description = "Globally unique, e.g. acme-tfstate-<account-id>-us-east-1" type = string validation { condition = can(regex("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", var.state_bucket_name)) error_message = "Bucket names are 3-63 lowercase letters, digits, dots and hyphens." } } resource "aws_s3_bucket" "state" { bucket = var.state_bucket_name lifecycle { prevent_destroy = true # losing state means Terraform forgets everything it manages } } resource "aws_s3_bucket_versioning" "state" { bucket = aws_s3_bucket.state.id versioning_configuration { status = "Enabled" # every state write is kept, so a bad apply can be rolled back } } 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_s3_bucket_public_access_block" "state" { bucket = aws_s3_bucket.state.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } data "aws_iam_policy_document" "tls_only" { statement { sid = "DenyInsecureTransport" effect = "Deny" actions = ["s3:*"] resources = [ aws_s3_bucket.state.arn, "${aws_s3_bucket.state.arn}/*", ] principals { type = "*" identifiers = ["*"] } condition { test = "Bool" variable = "aws:SecureTransport" values = ["false"] } } } resource "aws_s3_bucket_policy" "state" { bucket = aws_s3_bucket.state.id policy = data.aws_iam_policy_document.tls_only.json } output "state_bucket" { value = aws_s3_bucket.state.bucket } -
2Choose a unique bucket name
Bucket names are global across all AWS accounts; adding your account ID and region keeps them unique.
Run export TF_VAR_state_bucket_name="acme-tfstate-$(aws sts get-caller-identity --query Account --output text)-us-east-1" echo $TF_VAR_state_bucket_nameCheck:The name prints with your 12-digit account ID in it.
-
3Plan the bootstrap
Run cd bootstrap terraform init terraform planExpected output
# data.aws_iam_policy_document.tls_only will be read during apply # (config refers to values not yet known) <= data "aws_iam_policy_document" "tls_only" { ... # aws_s3_bucket.state will be created + resource "aws_s3_bucket" "state" { + bucket = "acme-tfstate-123456789012-us-east-1" + force_destroy = false ... # aws_s3_bucket_policy.state will be created # aws_s3_bucket_public_access_block.state will be created # aws_s3_bucket_server_side_encryption_configuration.state will be created # aws_s3_bucket_versioning.state will be created ... Plan: 5 to add, 0 to change, 0 to destroy.Check:Your bucket name appears instead of the example one.
-
4Create the bucket
The bootstrap's own state stays local. Keep
bootstrap/terraform.tfstatesafe (for example in a password manager or a separate, admin-only bucket): it's tiny and rarely changes.Run terraform applyCheck:Apply complete! Resources: 5 addedand thestate_bucketoutput shows your bucket name. -
5Create something with local state
app/main.tf terraform { required_version = ">= 1.10" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" } } } provider "aws" { region = "us-east-1" } # A small, free resource to have something in state resource "aws_ssm_parameter" "release" { name = "/shop/dev/release" type = "String" value = "1.0.0" } -
6Apply it locally
Run cd ../app terraform init terraform applyExpected output
# aws_ssm_parameter.release will be created + resource "aws_ssm_parameter" "release" { + arn = (known after apply) ... + name = "/shop/dev/release" + region = "us-east-1" + tags_all = (known after apply) + tier = (known after apply) + type = "String" + value = (sensitive value) ... } Plan: 1 to add, 0 to change, 0 to destroy.Check:After
yes:Apply complete! Resources: 1 addedand a localterraform.tfstatefile exists. -
7Add the S3 backend
Replace the bucket name with yours. Backend blocks can't use variables, because they're read before anything else.
keyis the path of this configuration's state inside the bucket: one key per root module and environment.app/backend.tf terraform { backend "s3" { bucket = "acme-tfstate-123456789012-us-east-1" # your bootstrap bucket key = "shop/dev/app.tfstate" # one key per root module and environment region = "us-east-1" encrypt = true use_lockfile = true # S3-native locking: no DynamoDB table needed } } -
8Migrate the state
Run terraform init -migrate-stateCheck:Terraform asks whether to copy the existing state to the new backend: answer
yes. It finishes by reporting that thes3backend was configured. -
9Confirm it's remote
Run terraform state list aws s3 ls s3://$TF_VAR_state_bucket_name/shop/dev/ rm terraform.tfstate terraform.tfstate.backupCheck:state liststill printsaws_ssm_parameter.release(now read from S3), andaws s3 lsshowsapp.tfstate. Delete the local copies so nobody uses them by mistake. -
10See the lock in action
terraform consoleholds the state lock while it's open. In a second terminal, try to plan from the same folder.With
use_lockfile = true, a run createsapp.tfstate.tflockwith a conditional write that only one writer can win. A second run that finds the lock stops with Error acquiring the state lock instead of overwriting the first run's changes, and can retry once the lock is gone.State locking: the second apply waits instead of corrupting the state Run # terminal 1 terraform console # terminal 2 terraform plan -lock-timeout=5sCheck:Terminal 2 fails with an error acquiring the state lock and shows who holds it. Exit the console in terminal 1 and the plan works. While locked, a
.tflockobject sits next to the state in S3. -
11See state versions
Change the parameter value in
main.tfto1.0.1, apply, then list the state file's versions.Run terraform apply aws s3api list-object-versions --bucket $TF_VAR_state_bucket_name --prefix shop/dev/app.tfstate --query "Versions[].[VersionId,LastModified]" --output tableCheck:At least two versions are listed. Any earlier version can be restored if a state write goes wrong.
Clean up
-
Destroy the app's resources (still from
app/):terraform destroy -
The bucket is protected on purpose. To remove it, edit
bootstrap/main.tf: delete thelifecycle { prevent_destroy = true }block and addforce_destroy = truetoaws_s3_bucket.state(this deletes every object version too). Then, frombootstrap/:terraform apply terraform destroy
Check for Destroy complete! Resources: 5 destroyed. At work, you would almost never delete a state bucket.
In production
What changes
| In this lab | In production |
|---|---|
| One bucket for one configuration | One state bucket per AWS account (usually one account per environment); keys like <repo>/<env>/<component>.tfstate |
| Your SSO user reads and writes state | CI roles have access to their own keys only; humans get read access, and break-glass write access |
| Bootstrap state kept by hand | Bootstrap run once by an admin (or by an account-vending pipeline) and documented |
aws:kms with the AWS-managed key |
A customer-managed KMS key with a key policy limited to the Terraform roles |
| You can delete the bucket | prevent_destroy, MFA delete or an SCP that denies s3:DeleteBucket on state buckets |
Recovering from a bad state write
- Stop all pipelines for that configuration.
- Find the last good version with
aws s3api list-object-versions. - Restore it (
aws s3api copy-objectfrom thatVersionIdonto the same key) and runterraform planto confirm the state matches reality.
Production checklist
- State lives in a remote backend with locking (
use_lockfile = trueon S3) - The state bucket has versioning, encryption, blocked public access and a TLS-only policy
- The state bucket can't be deleted by accident
- Each environment and component has its own state key; nothing shares a state file
- Access to state is limited: it contains resource attributes and sometimes secrets
- Everyone knows how to roll back to an earlier state version
Learn the concepts
- Terraform Remote State and Backends · Terraform Tutorial
- Terraform State · Terraform Tutorial
- Terraform import, moved and removed · Terraform Tutorial
- Terraform on AWS: Nonprod and Production Environments · Course
- Terraform in Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →