State Locking Fundamentals
What you'll learn: How Terraform prevents multiple users or processes from modifying infrastructure at the same time.
The Problem: Concurrent Modifications
When you run terraform apply, Terraform reads the state file, calculates changes, and writes updates back to state. But what happens if two team members run terraform apply simultaneously? Both would read the same initial state, make different changes, and try to write back — potentially overwriting each other's work and corrupting the state file.
This is where state locking comes in.
How State Locking Works
State locking is a mechanism that prevents concurrent operations on the same state file. When you execute terraform plan or terraform apply, Terraform attempts to acquire a lock on the state before making any changes. If another process already holds the lock, your operation waits or fails with an error.
Think of it like a bathroom door lock: only one person can be inside at a time. When someone's in there (lock engaged), others must wait. When they're done, they unlock the door for the next person.
Where Locking Happens
With local state storage (the default), Terraform creates a .terraform.tfstate.lock.info file to manage locks on your local filesystem. This prevents multiple terminal sessions on the same machine from conflicting, but doesn't help with team scenarios.
Remote state backends (which you'll learn later) provide more robust locking across multiple users and systems.
Why It Matters
Without state locking, you risk:
- Race conditions where two operations interfere with each other
- State corruption from incomplete or conflicting writes
- Lost changes when one apply overwrites another's work
Key Takeaway: State locking ensures only one Terraform operation can modify state at a time, preventing corruption and conflicts in single-user and team environments.