liveBook · Manning

Locking

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

State locking is the coordination mechanism that prevents concurrent Terraform operations from modifying the same state simultaneously.

Terraform state locking coordinates concurrent operations by telling the backend that only the currently running process may use the state. A second simultaneous operation fails instead of risking conflicting changes or a corrupted state file. section 5.6.2 section 6.4

Terraform normally manages locks automatically, so routine commands rarely require special handling. Backend configuration still matters: locking may be automatic or may require explicit setup, such as with S3. section 5.6.2 section 6.4.2

Concurrent applies and speculative plans

If two people start Terraform apply at the same time, one operation obtains the state lock and the other fails. A speculative plan used for testing, pull requests, or previewing code changes does not modify state, so automation commonly uses `-lock=false` for that run. Disabling locking for an operation that can change state remains dangerous. section 5.6.2 section 5.6.2

Use locking as part of production state management:

  • Enable locking whenever the backend requires explicit configuration; never use a backend without locking. section 6.4.2
  • Review backend-specific documentation, because built-in backends may require vendor-side configuration even when they support the required capabilities. section 6.4
  • Treat the local backend as a development convenience rather than a production solution. section 6.4
Figure 6.1 Basic backend configuration requirements

Use the backend configuration requirements overview to check locking alongside access restrictions, logging, encryption, and reliable tested backups. section 6.4.2

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Explains lock behavior, the unsafe override, speculative-plan exception, and backend-specific configuration requirements.
Examples
Uses simultaneous apply runs, the `-lock=false` flag, speculative plans, S3, and the local backend.
What it assumes
Assumes familiarity with Terraform operations and backends while distinguishing local development from production state management.
What you can do after
Operate/configure Terraform backends with locking and recognize when disabling locks is acceptable for non-mutating plans.
How it connects
Connects Terraform state with backends, concurrent applies, speculative plans, and production state management.

Also explained in

Compare how 18 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.