Subscribe

Storing Terraform state in S3 with native locking

Moving Terraform state from a local file to an S3 bucket with versioning and encryption, locking it with use_lockfile instead of a DynamoDB table, migrating the existing state, the IAM permissions it needs and what a lock error looks like.

Storing Terraform state in S3 with native locking

In the first hands-on Terraform post the state lived in a terraform.tfstate file next to the code. That's fine for one person on one laptop. It stops being fine the moment a second laptop or a CI job runs Terraform, because each of them has its own copy of the state and they don't know about each other.

In this blog we will move the state into an S3 bucket and turn on locking with use_lockfile, so two runs can't write the state at the same time. No DynamoDB table this time. Level: beginner, but you should have done a plan and apply before. I used Terraform 1.17.1 and AWS provider 6.73.0.

Where my own state lives

I'll be upfront. The Terraform for this blog's server still uses a local state file. It sits next to the code, it's in .gitignore, and I'm the only one who ever runs it through a small ./tf wrapper (that wrapper is in the import post). The day I want to run a plan from GitHub Actions, or from a second machine, it moves to S3 exactly like below. For anything with more than one person on it I wouldn't even start with local state.

No more DynamoDB table

For years the S3 backend needed two things: a bucket for the state and a DynamoDB table with a LockID key for the lock. Terraform 1.10 added S3 native locking, it became generally available in 1.11, and the dynamodb_table argument is deprecated now. The current S3 backend docs say DynamoDB-based locking "will be removed in a future minor version". So for anything new, skip the table.

Native locking uses S3 conditional writes. When Terraform wants the lock it writes a small object called <key>.tflock next to the state, with a condition that says "only if this object does not exist yet". If someone else already has the lock, S3 refuses the write and Terraform stops. When the run ends, it deletes the lock object.

The bucket

The state bucket is created with Terraform too, from its own tiny project. I call it bootstrap.

terraform {
  required_version = ">= 1.11"

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

provider "aws" {
  region = "ap-south-1"
}

data "aws_caller_identity" "current" {}

resource "aws_s3_bucket" "state" {
  bucket = "tfstate-${data.aws_caller_identity.current.account_id}-ap-south-1"

  lifecycle {
    prevent_destroy = true
  }
}

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

  versioning_configuration {
    status = "Enabled"
  }
}

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

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

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
}

resource "aws_s3_bucket_ownership_controls" "state" {
  bucket = aws_s3_bucket.state.id

  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "state" {
  bucket = aws_s3_bucket.state.id

  rule {
    id     = "old-state-versions"
    status = "Enabled"

    filter {}

    noncurrent_version_expiration {
      noncurrent_days           = 90
      newer_noncurrent_versions = 20
    }
  }
}

output "state_bucket" {
  value = aws_s3_bucket.state.bucket
}

This is close to the bucket I use for the blog's nightly MySQL backups, same account ID in the name trick (bucket names are global, the account ID makes a clash unlikely).

Versioning is the important one. Every apply writes a new version of the state object, so if a state ever gets broken you can go back to the one before. The lifecycle rule keeps old versions for 90 days but always keeps the newest 20, so the bucket doesn't grow forever. prevent_destroy is there because deleting this bucket by accident would orphan every project that keeps state in it.

Run it the normal way.

cd bootstrap
terraform init
terraform plan -out=bootstrap.tfplan
terraform apply bootstrap.tfplan

Yes, the bootstrap project's own state is local. It's the chicken and egg thing. I'm fine with that, it's six resources and I can always import them again. Some people migrate it into same bucket after the first apply, which also works.

The backend block

Now go to the project from the first post and add a backend.tf.

terraform {
  backend "s3" {
    bucket       = "tfstate-111122223333-ap-south-1"
    key          = "hands-on/web.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

Put your own bucket name in. You can't use variables inside a backend block, which annoys everyone the first time. If you need different values per environment, leave them out and pass them at init time with -backend-config=... or a small .hcl file.

key is the path of the state object inside the bucket. I use <project>/<name>.tfstate so one bucket holds many projects. use_lockfile = true is the line this post is about. It's false by default, so without it there's no locking at all.

Migrating the local state

With the backend block in place, run init with -migrate-state.

terraform init -migrate-state

Terraform notices the backend changed and asks if it should copy the existing local state to S3. Answer yes. After that, check that the state really is there and that nothing in the code wants to change.

aws s3 ls s3://tfstate-111122223333-ap-south-1/hands-on/
terraform plan

The plan should say no changes. If it does, the local terraform.tfstate is now just an old copy. I'd keep it somewhere outside the folder for a few days and then delete it, so nobody runs a command against it by mistake.

Permissions

Whoever runs Terraform needs access to the state object and to the lock object. The lock needs delete as well, because Terraform removes it at the end of a run. The S3 backend docs list s3:GetObject, s3:PutObject and s3:DeleteObject on the lock file.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::tfstate-111122223333-ap-south-1"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::tfstate-111122223333-ap-south-1/hands-on/web.tfstate"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::tfstate-111122223333-ap-south-1/hands-on/web.tfstate.tflock"
    }
  ]
}

Notice there's no delete on the state itself. Terraform never deletes the state object, and with versioning on, nobody should.

If you're setting up a new account and users from scratch, the safe new AWS account post covers where these permissions should be attached.

Seeing the lock work

I wanted to see the lock with my own eyes before trusting it. I didn't want a real bucket for this, so I ran it against moto, a local S3 mock, with fake credentials. I started one terraform plan, and while it was still running I started a second one from the same folder. The second one failed straight away.

Error: Error acquiring the state lock

Error message: operation error S3: PutObject, https response error
StatusCode: 412, RequestID: ..., HostID: ...,
api error PreconditionFailed: At least one of the pre-conditions you
specified did not hold
Lock Info:
  ID:        5a6bbf5f-2e8d-dbfd-b564-b9c5994a3354
  Path:      tfstate-111122223333-ap-south-1/hands-on/web.tfstate
  Operation: OperationTypePlan
  Who:       me@my-mac.local
  Version:   1.17.1
  Created:   2026-11-19 06:41:52.554741 +0000 UTC
  Info:


Terraform acquires a state lock to protect the state from being written
by multiple users at the same time. Please resolve the issue above and try
again. For most commands, you can disable locking with the "-lock=false"
flag, but this is not recommended.

I cut the request IDs and changed my hostname, the rest is as printed. The 412 PreconditionFailed is the conditional write doing its job. While the first plan was running there was one object in the bucket, hands-on/web.tfstate.tflock, with that same lock info in it as JSON. Once the first plan finished the object was gone and the bucket was empty again. Plan doesn't write state, only apply does, so nothing else showed up.

Even a plan takes the lock. That surprised me a bit at first, but it makes sense: plan reads the state, and you don't want to read it halfway through someone else's apply.

When a lock gets stuck

If Terraform gets killed in the middle of a run (laptop lid closed, CI job cancelled), the .tflock object stays behind and every run after that fails with the error above. First make sure nobody is really running anything. Then use the ID from the error.

terraform force-unlock 5a6bbf5f-2e8d-dbfd-b564-b9c5994a3354

It asks for confirmation and deletes the lock. Don't reach for -lock=false instead, that just skips the safety for one run and leaves the stuck lock where it is.

Getting an old state back

This is what versioning is for. List the versions of the state object, download the one you want and look at it before you do anything.

aws s3api list-object-versions \
  --bucket tfstate-111122223333-ap-south-1 \
  --prefix hands-on/web.tfstate

aws s3api get-object \
  --bucket tfstate-111122223333-ap-south-1 \
  --key hands-on/web.tfstate \
  --version-id <version-id> \
  old.tfstate

Pushing it back is terraform state push old.tfstate. Terraform checks the serial number and refuses to push an older state over a newer one unless you add -force. I'd only do that after reading both files carefully, and with nobody else running Terraform at that moment.

That's it. One bucket, one line of use_lockfile = true, and no table to pay for or forget about.