Skip to content
Optimal Lab

DevOps · interactive

Terraform state and locking

Terraform keeps a state file mapping your code to real resources. It's how it knows what to change or delete. If two people apply at once without a lock, one can overwrite the other's state and lose track of real infrastructure.

Ana

idle

Ben

idle

terraform.tfstate (remote)

vpcdb

What actually exists in the cloud

vpcdb

The shared state file (in S3) records what Terraform created: a VPC and a database.

State locking

step 1 of 7

Step 1 of 4

  1. 1

    State maps code to reality

    Resource addresses to cloud ids and attributes. Without it, Terraform can't update or delete what it made.

    It can contain secrets: protect it.

  2. 2

    Use a remote backend

    S3, GCS, Terraform Cloud: one shared copy with versioning, not files on laptops.

    backend "s3" { bucket = …, use_lockfile = true }

  3. 3

    Lock during apply

    Only one plan/apply holds the lock; others fail fast and retry. Run applies from CI so it's one at a time anyway.

    force-unlock only if you're sure.

  4. 4

    Repair with import and state commands

    terraform import adopts an orphan; state mv and rm fix addresses. Split large states so one mistake has a small blast radius.

    terraform import aws_elasticache_cluster.cache …

In production

Tools and technologies

Remote state with locking is standard for any team using Terraform.

Not tied to one language — use these names when you search docs or design a system.