HashiCorp Terraform Associate (004) · Section 6 · 10% of the exam
Describe state locking
One of the objectives of the HashiCorp Certified: Terraform Associate (004) exam, in the section “Terraform state management”. Here is what it covers, the points to remember and a question to try.
What it covers
Terraform keeps a state file that maps your configuration to real objects. This lesson covers the default local backend, how state locking prevents two runs from writing at once, and how to move state to a remote backend with the backend block, partial configuration and terraform init.
Points to remember
- With no backend or cloud block, Terraform uses the local backend and stores state in terraform.tfstate in the working directory.
- The local backend keeps the previous state in terraform.tfstate.backup and non-default workspaces under terraform.tfstate.d.
- Terraform locks state automatically for operations that could write it, if the backend supports locking.
- -lock-timeout waits for a lock; -lock=false skips locking and is not recommended; force-unlock LOCK_ID releases a stale lock.
- S3 native locking is use_lockfile = true (a .tflock object); DynamoDB locking is deprecated.
Try a question
A team uses the S3 backend with no locking settings. Two engineers ran terraform apply for the same state key within seconds of each other, and the state afterwards lost one engineer's resources. The team wants to prevent a repeat on a Terraform version that supports it, without adding new AWS services. What should they do?
- ACreate a DynamoDB table with a
LockIDkey and setdynamodb_tablein the backend block - BEnable bucket versioning so older states are kept
- CSet
use_lockfile = truein the backend block and grant access to the lock object - DRun
terraform apply -lock=falseto avoid contention
Show the answer
C. S3 locking is opt-in. use_lockfile = true writes a .tflock object next to the state, and the role needs s3:GetObject, s3:PutObject and s3:DeleteObject on it. Bucket versioning is still recommended for recovery. DynamoDB locking is deprecated.
Written for practice in the style of the exam: never a question from the real exam.
In the course
The lesson Local backend, state locking and remote state teaches this objective (about 40 minutes), and 24 practice questions test it. The course has lessons, exam-style questions, timed practice exams and an AI tutor for every objective, and a pass prediction that tells you when you're ready to book.