Lock Your Terraform State the Moment a Second Engineer Touches It

Local state files with no locking mechanism are fine solo. The moment a second person runs terraform apply, you're one race condition away from a corrupted state file and a very bad afternoon.

The Problem

Terraform state tracks exactly what your infrastructure looks like. Two people running terraform apply at the same moment, both reading and writing that same state file, is how you end up with duplicated resources, orphaned infrastructure, or a state file that no longer matches reality. Local .tfstate files have zero protection against this by default.

Set Up a Remote Backend With Locking

Move state off local disk and into a backend that supports locking, S3 with a DynamoDB table for lock coordination is the standard AWS pattern:

terraform {
  backend "s3" {
    bucket         = "your-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

The DynamoDB table just needs a single primary key (LockID, type String). Terraform handles acquiring and releasing the lock automatically — you don't manage it manually.

What Locking Actually Prevents

When someone runs apply, Terraform writes a lock entry before touching state. A second apply attempted at the same time fails im is locked" error instead ofsilently racing the first one. It's a hard stop, not a warning — exactly what you want when the failure mode is a corrupted production state file.

If You're Already Past Two Engineers Without This

Migrating an existing project to a remote backend is low-risk: run terraform init -migrate-state after adding the backend block, conted, and commit the backend config.Do this before your next infrastructure change, not after the state conflict that finally forces the issue.

The EaseCloud Team

The EaseCloud Team

274 articles