Module 6: Terraform State Management

Lesson 6.2: State Locking

Plain language

State locking stops two operations from writing the same state at the same time. If one process holds the lock, others fail immediately, or wait if you pass -lock-timeout.

Under the hood

  • Operations that lock: any operation that could write state takes the lock automatically, including plan, apply, destroy, import, state mv and state rm, console, and refresh-only runs.
  • Backend support: not every backend supports locking. Check the backend's documentation.
Backend Locking mechanism
local OS file lock (same machine only)
s3 use_lockfile = true: an S3 lock object. Native S3 lock files were added in 1.10 (experimental) and became generally available in 1.11, when DynamoDB-based locking was deprecated.
azurerm Blob lease
gcs Lock file in the bucket
pg PostgreSQL advisory locks
consul, kubernetes Native locking
http Only if the server implements the lock endpoints
HCP Terraform (cloud block) Workspace locking, built in

When a lock is held, Terraform errors with the lock ID, path, operation, and holder:

Text
Error: Error acquiring the state lock
Lock Info:
  ID:        3a8e...
  Operation: OperationTypeApply
  Who:       travis@laptop
Option Use
-lock-timeout=60s Wait up to 60 seconds for the lock before failing. Good for CI queues.
-lock=false Skip locking. Dangerous. Avoid it.
terraform force-unlock LOCK_ID Remove a lock that won't release because the process crashed. Requires the lock ID. Only use it when you're sure no operation is running.