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

Members can save this page, take notes and track progress. See membership · Sign 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.

Before: local stateYour laptopterraform.tfstate: the only copyTeammatecan't see itCI pipelinecan't see itAfter: shared S3 backendYouTeammateCI pipelineS3 bucketshop/dev/app.tfstateapp.tfstate.tflockexists while one applies
Before and after: one laptop's state file versus a shared, locked S3 backend

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.

bootstrap/ (run once)bootstrap/main.tfcreates the bucketterraform.tfstatelocal, keep it safeS3 bucket acme-tfstate-…Versioningevery write keptSSE-KMSencrypted at restPublic accessfully blockedBucket policyTLS onlyshop/dev/app.tfstateprevent_destroy on the bucketapp/backend.tfbackend "s3", use_lockfileterraform.tfstatelocal, before movinginit -migrate-statecopies state to S3
Two configurations: bootstrap creates a protected state bucket, app moves its state into it

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

Download starter filesDownload finished project

Steps

  1. 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_destroy stops an accidental terraform 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
    }
    
  2. 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_name
    
    Check:

    The name prints with your 12-digit account ID in it.

  3. 3Plan the bootstrap

    Run
    cd bootstrap
    terraform init
    terraform plan
    

    Expected 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.

  4. 4Create the bucket

    The bootstrap's own state stays local. Keep bootstrap/terraform.tfstate safe (for example in a password manager or a separate, admin-only bucket): it's tiny and rarely changes.

    Run
    terraform apply
    
    Check:

    Apply complete! Resources: 5 added and the state_bucket output shows your bucket name.

  5. 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"
    }
    
  6. 6Apply it locally

    Run
    cd ../app
    terraform init
    terraform apply
    

    Expected 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 added and a local terraform.tfstate file exists.

  7. 7Add the S3 backend

    Replace the bucket name with yours. Backend blocks can't use variables, because they're read before anything else. key is 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
      }
    }
    
  8. 8Migrate the state

    Run
    terraform init -migrate-state
    
    Check:

    Terraform asks whether to copy the existing state to the new backend: answer yes. It finishes by reporting that the s3 backend was configured.

  9. 9Confirm it's remote

    Run
    terraform state list
    aws s3 ls s3://$TF_VAR_state_bucket_name/shop/dev/
    rm terraform.tfstate terraform.tfstate.backup
    
    Check:

    state list still prints aws_ssm_parameter.release (now read from S3), and aws s3 ls shows app.tfstate. Delete the local copies so nobody uses them by mistake.

  10. 10See the lock in action

    terraform console holds the state lock while it's open. In a second terminal, try to plan from the same folder.

    With use_lockfile = true, a run creates app.tfstate.tflock with 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.

    AliceS3Bobterraform applystarts firstcreates lockconditional writeapplies changessaves stateremoves the lockapp.tfstate.tflock existsterraform applystarts laterlock checkError: state lockedretryafter the lock is goneuse_lockfile = true: S3 itself guarantees only one writer, no DynamoDB table needed
    State locking: the second apply waits instead of corrupting the state
    Run
    # terminal 1
    terraform console
    
    # terminal 2
    terraform plan -lock-timeout=5s
    
    Check:

    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 .tflock object sits next to the state in S3.

  11. 11See state versions

    Change the parameter value in main.tf to 1.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 table
    
    Check:

    At least two versions are listed. Any earlier version can be restored if a state write goes wrong.

Clean up

  1. Destroy the app's resources (still from app/):

    terraform destroy
    
  2. The bucket is protected on purpose. To remove it, edit bootstrap/main.tf: delete the lifecycle { prevent_destroy = true } block and add force_destroy = true to aws_s3_bucket.state (this deletes every object version too). Then, from bootstrap/:

    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

  1. Stop all pipelines for that configuration.
  2. Find the last good version with aws s3api list-object-versions.
  3. Restore it (aws s3api copy-object from that VersionId onto the same key) and run terraform plan to confirm the state matches reality.

Production checklist

  • State lives in a remote backend with locking (use_lockfile = true on 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

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake