All guides

Where to keep Terraform state, and how to lock it

The state file is Terraform's record of what it built. Lose it, or let two people write to it at once, and Terraform no longer knows what it manages.

Close-up of code on a screen in many colours

What the state file is

Terraform maps every resource in your code to a real resource in your cloud, and writes that map to the state file. The file often holds secrets in plain text, such as database passwords and generated keys. Treat it like a credential.

Three rules

  1. Never in Git, never on a laptop. Add *.tfstate to .gitignore on day one.
  2. A remote backend with locking and versioning. Locking stops two runs from writing at once. Versioning lets you go back when a run goes wrong.
  3. One state per environment. A mistake in the test environment should not be able to touch production.

A backend on each cloud

On AWS, state lives in an S3 bucket. Since Terraform 1.10 the S3 backend can lock with a lock file in the bucket itself; older setups use a DynamoDB table for the lock.

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "prod/network/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
  }
}

Turn on versioning for the bucket as well. On Azure, the azurerm backend keeps state in a storage container and locks it with a blob lease. On Google Cloud, the gcs backend locks by itself; switch on object versioning for the bucket.

Split the state

One state for everything means every plan reads everything, and every mistake can reach everything. Split by environment first, then by the parts that change at different speeds: the network rarely, the application every week. The key above shows the pattern: prod/network, prod/app.

When a lock is stuck

A run that was killed can leave its lock behind. Check that nobody else is running, then release it:

terraform force-unlock LOCK_ID

If you reach for that command every week, the real problem is that people run Terraform from their own machines.

Run it from one place

Let the pipeline run terraform plan on every pull request and terraform apply after the merge. Then only the pipeline's role needs write access to the state, and every change to your cloud has a review behind it.

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides