StackPractices
intermediate By Mathias Paulenko

Store Terraform Remote State in S3 with Locking

How to configure Terraform remote state on S3 with native locking, encryption, and versioning — plus state isolation, workspaces, CI/CD, and DynamoDB migration.

Topics: devops

Overview

Terraform keeps a .tfstate file that maps your code to real infrastructure. Leave it on a laptop and two people can’t safely run apply at once — and whoever opens the file can read any plaintext secrets inside. The fix is a remote backend, and on AWS that means S3: durable, versioned, encrypted, and reachable from CI. Since Terraform 1.10, the S3 backend locks state natively with a .tflock object, so a DynamoDB table is no longer required (the old dynamodb_table argument is deprecated).

When to Use

  • Several engineers applying changes against the same state
  • CI/CD pipelines running Terraform in GitHub Actions, Jenkins, or GitLab CI
  • Production infrastructure where state must be encrypted and locked
  • Multi-environment setups that need a separate state file per environment
  • Anywhere you want S3 versioning as a rollback path for a corrupted state

When NOT to Use

  • Solo, local-only experiments — local state is simpler
  • HCP Terraform or Atlantis already manages your state
  • Non-AWS infrastructure — use the Azure Blob or GCS backend instead
  • Throwaway prototypes you’ll delete the same day

How It Works

The state file is a JSON document recording every resource Terraform created, so a later run can diff “what exists” against “what the code wants”. When plan or apply starts, the backend writes a .tflock object next to the state object; a second run that finds it fails immediately instead of trampling the state mid-write. Two safety rails matter here: prevent_destroy on the bucket stops a stray terraform destroy from wiping every environment’s history, and S3 versioning lets you recover a state file even after a bad apply overwrote it.

flowchart diagram: terraform plan/apply

If you’re coming from an older setup with dynamodb_table, migrating is a one-liner — see the legacy variant below. The broader operational concerns (drift detection, reviewed applies, policy as code) are covered in the Terraform production guide.

Solution

A complete runnable version (bootstrap plus per-environment backend examples) lives in the companion repository.

Bootstrap the state bucket

# bootstrap.tf — Run this once to create the S3 bucket.
# Keep it in a separate root module or a separate repo.

resource "aws_s3_bucket" "terraform_state" {
  bucket = "my-company-terraform-state"

  lifecycle {
    prevent_destroy = true  # Losing this bucket loses every environment's history
  }
}

resource "aws_s3_bucket_versioning" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_s3_bucket_public_access_block" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

Configure the S3 backend

# backend.tf
terraform {
  required_version = ">= 1.10.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "infrastructure/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true   # Native locking, no DynamoDB table needed
    encrypt      = true
  }
}

Initialize with the backend

# First-time init with the S3 backend
terraform init

# Migrating existing local state to S3
terraform init -migrate-state

# Moving from dynamodb_table to use_lockfile
terraform init -reconfigure

State isolation with key prefixes

# Each environment gets its own state object in the same bucket

# backend.tf for dev
terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "dev/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
    encrypt      = true
  }
}

# backend.tf for production
terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "prod/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
    encrypt      = true
  }
}

Using partial backend configuration

# backend.tf — leave the block empty and pass values at init time
terraform {
  backend "s3" {}
}
terraform init \
  -backend-config="bucket=my-company-terraform-state" \
  -backend-config="key=dev/terraform.tfstate" \
  -backend-config="region=us-east-1" \
  -backend-config="use_lockfile=true" \
  -backend-config="encrypt=true"

Backend credentials with environment variables

export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="us-east-1"

# Terraform picks up AWS credentials from the environment automatically
terraform init
terraform plan
terraform apply

Static keys work for local runs, but in CI prefer OIDC or an IAM instance role — see the GitHub Actions example below.

Using workspaces for environment isolation

Workspaces don’t need any special backend key — the S3 backend stores each workspace’s state under env:/{workspace}/{key} automatically. You can’t interpolate terraform.workspace inside a backend block (backend config is evaluated before any expressions), so just declare a plain key:

# backend.tf — one key; workspaces namespace it automatically
terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "infrastructure/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
    encrypt      = true
  }
}
# Create and switch workspaces
terraform workspace new dev
terraform workspace new staging
terraform workspace new production

# State lands at env:/dev/infrastructure/terraform.tfstate
terraform workspace list
terraform workspace select production

terraform plan
terraform apply

Conditional resources by workspace

# main.tf — terraform.workspace IS available here (just not in backend blocks)
locals {
  env_config = {
    dev = {
      instance_count = 1
      instance_type  = "t3.micro"
    }
    staging = {
      instance_count = 2
      instance_type  = "t3.small"
    }
    production = {
      instance_count = 3
      instance_type  = "t3.medium"
    }
  }

  config = local.env_config[terraform.workspace]
}

resource "aws_instance" "app" {
  count         = local.config.instance_count
  instance_type = local.config.instance_type
  ami           = data.aws_ami.ubuntu.id

  tags = {
    Name        = "app-${terraform.workspace}-${count.index + 1}"
    Environment = terraform.workspace
  }
}

What a lock conflict looks like

# A second run that finds an active lock fails fast:
# Error: Error acquiring the state lock
# Lock Info:
#   Path:    my-company-terraform-state/dev/terraform.tfstate
#   LockID:  abc123-def456

# If a crashed run left a stale lock behind, remove it (check nothing is actually running first)
terraform force-unlock abc123-def456

CI/CD with GitHub Actions

# .github/workflows/terraform.yml
# Prefer OIDC (configure-aws-credentials with role-to-assume) over
# static access keys in real pipelines.
name: Terraform

on:
  pull_request:
    paths: ["terraform/**"]
  push:
    branches: [main]
    paths: ["terraform/**"]

jobs:
  terraform:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: terraform
    steps:
      - uses: actions/checkout@v4

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.11"

      - name: Terraform Init
        run: terraform init

      - name: Terraform Format
        run: terraform fmt -check

      - name: Terraform Plan
        run: terraform plan -no-color
        env:
          TF_VAR_environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'dev' }}

      - name: Terraform Apply
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply -auto-approve

Day-to-day state operations

# List resources tracked in state
terraform state list

# Inspect one resource
terraform state show aws_instance.app[0]

# Rename a resource without destroying it
terraform state mv aws_instance.old aws_instance.new

# Drop a resource from state (leaves the real object running)
terraform state rm aws_instance.app[0]

# Pull remote state to a local file (handle with care, it's plaintext)
terraform state pull > terraform.tfstate

# Push a local state file back to S3
terraform state push terraform.tfstate

Variants

Legacy: DynamoDB locking (Terraform < 1.10)

Older setups used a DynamoDB table for locking. It still works, but dynamodb_table is deprecated — plan to move to use_lockfile when you upgrade Terraform. To migrate, remove dynamodb_table, set use_lockfile = true, and run terraform init -reconfigure; keep the table around until every workspace has migrated, then delete it.

# bootstrap addition for the legacy setup
resource "aws_dynamodb_table" "terraform_locks" {
  name         = "terraform-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"

  attribute {
    name = "LockID"
    type = "S"
  }
}

# backend.tf (legacy)
terraform {
  backend "s3" {
    bucket         = "my-company-terraform-state"
    key            = "infrastructure/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Cross-region replication for state

# Replicate state to a second region for disaster recovery.
# Replication needs a provider alias — `region` is not an aws_s3_bucket argument.

provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

resource "aws_s3_bucket" "terraform_state_backup" {
  provider = aws.west
  bucket   = "my-company-terraform-state-backup"
}

resource "aws_iam_role" "replication" {
  name = "terraform-state-replication"
  # Trust + policy documents omitted — see AWS docs on S3 replication roles
}

resource "aws_s3_bucket_replication_configuration" "state_replication" {
  bucket = aws_s3_bucket.terraform_state.id
  role   = aws_iam_role.replication.arn

  rule {
    status = "Enabled"
    destination {
      bucket        = aws_s3_bucket.terraform_state_backup.arn
      storage_class = "STANDARD"
    }
  }
}

Using assume role for backend access

terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "infrastructure/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
    encrypt      = true
    assume_role = {
      role_arn = "arn:aws:iam::123456789012:role/TerraformBackendAccess"
    }
  }
}

Multiple state files for different components

# Directory structure — one backend per component per environment
terraform/
├── modules/
│   ├── vpc/
│   ├── eks/
│   └── rds/
├── environments/
│   ├── dev/
│   │   ├── vpc/
│   │   │   ├── backend.tf   # key = "dev/vpc/terraform.tfstate"
│   │   │   └── main.tf
│   │   ├── eks/
│   │   │   ├── backend.tf   # key = "dev/eks/terraform.tfstate"
│   │   │   └── main.tf
│   │   └── rds/
│   │       ├── backend.tf   # key = "dev/rds/terraform.tfstate"
│   │       └── main.tf
│   └── production/
│       └── ...

Best Practices

  • Turn on use_lockfile — it costs nothing and removes a DynamoDB table from your bill.
  • Keep S3 versioning enabled — it’s your only undo button after a bad apply.
  • Encrypt at rest and block public access — state files carry plaintext secrets, IPs, and ARNs.
  • Set prevent_destroy on the state bucket — deleting it’s the one mistake you can’t recover from.
  • Split state by environment, then by component (VPC, EKS, RDS) — smaller blast radius, faster plans.
  • Never commit terraform.tfstate to git — it’s not mergeable and leaks secrets.
  • Reserve force-unlock for confirmed stale locks — verify no run is active first.
  • For workspace-driven isolation, see Isolate Environments with Terraform Workspaces.

Common Mistakes

  • Relying on DynamoDB forever: dynamodb_table is deprecated since the native lockfile landed in Terraform 1.10. Migrate and drop the table.
  • No S3 versioning: one corrupted overwrite and there’s nothing to roll back to. Turn it on before the first real apply.
  • Interpolating terraform.workspace in the backend block: backend config can’t use expressions — the backend namespaces workspaces under env:/ on its own.
  • One giant state file: slow plans and a blast radius covering every environment. Split by environment and component.
  • Committing state to git: plaintext secrets plus merge conflicts. Remote backend, always.
  • Skipping prevent_destroy: one careless destroy in the bootstrap module wipes every environment’s history.
  • Blind force-unlock: if another run actually holds the lock, forcing it corrupts state. Confirm nothing is actually running first.

Frequently Asked Questions

What is Terraform state?

A JSON file mapping the resources in your code to the real objects Terraform created. It's how Terraform knows what to update or destroy on the next run.

What is state locking?

A guard that stops two Terraform runs from writing the same state file at once. On S3, the backend writes a .tflock object; whoever holds it proceeds, everyone else fails fast.

Is dynamodb_table deprecated?

Yes. Terraform 1.10 added native S3 locking (use_lockfile = true), and HashiCorp now marks dynamodb_table as deprecated. New setups shouldn't create the table; existing ones can migrate with terraform init -reconfigure after swapping the argument.

How do I migrate from local to remote state?

Add the backend "s3" block to your config and run terraform init -migrate-state. Terraform copies the local state up to S3 and continues from there.

Can I use the same S3 bucket for multiple projects?

Yes — give each project its own key (e.g., project-a/terraform.tfstate, project-b/terraform.tfstate). Each key is an independent state object, so keep IAM and prevent_destroy consistent across the bucket.