EcoMarket's state now lives in a remote backend: shared, encrypted and versioned. That solves three of the four problems with local state, but it opens a new one that did not exist before: if the state belongs to everybody, everybody can write it at the same time. Two people applying in the same minute, or a manual apply coinciding with a nightly pipeline, are enough to leave the state inconsistent and the infrastructure duplicated. The mechanism that prevents this is state locking, and in this lesson you are going to see all of it: how a lock is acquired, what the lock file contains, what the "Error acquiring the state lock" message means exactly, when it is legitimate to force a release, and why -lock=false is almost never the answer you are looking for.
- The race condition: two
apply runs at once
apply runs at onceImagine EcoMarket with no locking. It is 10:15 on a Tuesday. Alice adds the staging images bucket; Luke, in parallel, raises the number of web instances in the same environment. Both run terraform apply two minutes apart, against the same remote state.
sequenceDiagram
participant A as Alice
participant S as Remote state<br/>serial 12
participant I as Infrastructure
participant L as Luke
A->>S: reads state (serial 12)
L->>S: reads state (serial 12)
Note over A,L: both start from the SAME snapshot
A->>I: creates ecomarket-staging-images
I-->>A: id = ...-images-9f3a2b1c
L->>I: scales the web tier to 4 instances
I-->>L: ok
A->>S: writes state (serial 13)<br/>web=2, bucket=yes
L->>S: writes state (serial 13)<br/>web=4, bucket=DOES NOT EXIST
Note over S: Luke's write OVERWRITES Alice's
Note over S,I: the bucket really exists,<br/>but the state does not know it
The result, the next day:
| What really exists | What the state believes | Consequence |
|---|---|---|
The bucket ecomarket-staging-images-9f3a2b1c |
That it does not exist | Orphaned resource: nobody manages it, nobody will destroy it, and it keeps billing |
| The web tier with 4 instances | 4 instances | Correct, by accident |
| — | — | Alice's next apply creates the bucket again, with a different random suffix |
And there are worse variants. If the two writes coincide at exactly the same moment, the state object can end up truncated or with invalid JSON, and then no plan works until somebody restores an earlier version from the bucket. With real cloud resources, the bill and the fright are proportionate.
The root cause is not concurrency itself: it is that the sequence read → decide → write is not atomic. Locking makes it atomic, by force.
- What a state lock is and how Terraform implements it
A state lock is a mutual-exclusion marker that Terraform places in the backend before any operation that might write the state, and removes when it finishes. While the marker exists, any other Terraform trying to operate on that same state finds the door closed.
The cycle has three phases:
flowchart LR
A["1. ACQUIRE<br/>conditional write<br/>in the backend"] --> B["2. OPERATE<br/>refresh, plan,<br/>apply, write state"]
B --> C["3. RELEASE<br/>delete the marker"]
B -. "failure, Ctrl+C,<br/>killed process" .-> D["ORPHANED LOCK"]
D -. "force-unlock" .-> C
style D fill:#ffe5e5,stroke:#c53030
- Acquire. Terraform tries to create the marker conditionally: "create this object only if it does not exist". That condition is what makes the mechanism reliable; if two processes try at once, the backend guarantees that only one wins. In S3 with
use_lockfileit is a conditional write of a.tflockobject; in DynamoDB, aPutItemwithattribute_not_exists(LockID); in Azure, a lease on the blob; in GCS, a write with a generation precondition. - Operate. For as long as the operation lasts, the lock stays. Object-based backends renew nothing: the marker persists until it is deleted. Lease-based ones, like Azure, do renew periodically, so a dead process eventually releases the lock only when the lease expires.
- Release. On finishing — successfully or with a handled error — Terraform deletes the marker. If the process dies abruptly, the marker stays: that is the orphaned lock of section 9.
Two nuances that avoid common misunderstandings:
- The lock protects the state, not the infrastructure. If two people modify the same resource from the web console, the lock knows nothing about it. It only serialises Terraform operations against that state.
- The lock is per state, not per project. If EcoMarket keeps
networkandappin separate states, somebody can applyappwhile another appliesnetwork. It is one more reason to separate states per component.
- Which commands lock and which do not
| Command | Does it lock? | Type | Why |
|---|---|---|---|
terraform apply |
Yes | Write | It modifies the state |
terraform destroy |
Yes | Write | It modifies the state |
terraform plan |
Yes | Write | It refreshes, and some backends require a lock for consistency |
terraform import |
Yes | Write | It adds resources to the state |
terraform state mv / rm / push / replace-provider |
Yes | Write | They modify the state |
terraform refresh (deprecated) |
Yes | Write | It rewrites the state |
terraform apply -refresh-only |
Yes | Write | It rewrites the state |
terraform state list / show / pull |
No | Read | They only read |
terraform output |
No | Read | It only reads |
terraform show |
No | Read | It only reads |
terraform validate / fmt / console |
No | — | They do not touch the state |
terraform init |
Only if it migrates state | — | The migration is a write |
The plan row deserves an explanation, because it is surprising: a plan does not write the state as of Terraform 0.15.4, but it does acquire the lock. The reason is consistency: if somebody applied halfway through your refresh, your plan would describe a reality that no longer exists. Terraform would rather make you wait than give you a lying plan.
A very concrete practical consequence: at EcoMarket, a plan from one PR can block another's apply. With states separated by environment and component, that contention all but disappears. If it still gets in the way, the answer is -lock-timeout, not -lock=false (section 8).
- Backends with and without locking
| Backend | Locking | Mechanism | Extra resources |
|---|---|---|---|
local |
Yes | .terraform.tfstate.lock.info + the system's flock |
None |
s3 |
Yes | .tflock object (use_lockfile) or a DynamoDB item |
None / one table |
azurerm |
Yes | Native blob lease | None |
gcs |
Yes | Conditional write by generation | None |
kubernetes |
Yes | A Lease object from the API |
None |
consul |
Yes | A Consul session | None |
pg |
Yes | PostgreSQL advisory lock | None |
cloud / remote |
Yes | The service's run queue | None |
http |
Optional | Depends on the server implementing LOCK/UNLOCK |
Your own service |
Practically every serious backend supports locking. The one to watch is http: if the service behind it does not implement lock_address and unlock_address, you have shared state without mutual exclusion, which is the worst possible combination: everyone can write and nothing stops them.
- Configuring locking in practice
5.1. S3 with native file-based locking
The modern option. It requires no additional resource:
terraform {
backend "s3" {
bucket = "ecomarket-tfstate-eu-west-1"
key = "ecomarket/dev/app/terraform.tfstate"
region = "eu-west-1"
encrypt = true
kms_key_id = "arn:aws:kms:eu-west-1:111122223333:key/a1b2c3d4-5566-7788-99aa-bbccddeeff00"
# Native locking: Terraform creates and deletes the object
# ecomarket/dev/app/terraform.tfstate.tflock
# using S3's conditional write (If-None-Match). Only one
# writer can create it: that is the mutual exclusion.
use_lockfile = true
}
}Requirements and consequences:
- The role needs
s3:PutObject,s3:GetObjectands3:DeleteObjectover*.tflock(remember the policy in section 12 of the previous lesson: deletion is granted only over the lock files, never over the state). - The lock object lives next to the state, so you can see it with a simple
aws s3 ls. - It needs a recent version of Terraform (1.10+) or OpenTofu. If your organisation is on 1.9.8 like EcoMarket, it is not available yet: use DynamoDB.
5.2. S3 with DynamoDB: the classic variant
terraform {
backend "s3" {
bucket = "ecomarket-tfstate-eu-west-1"
key = "ecomarket/dev/app/terraform.tfstate"
region = "eu-west-1"
encrypt = true
# The table must exist BEFORE the init and must have as its
# partition key a string attribute called exactly "LockID".
dynamodb_table = "ecomarket-tfstate-locks"
}
}# bootstrap/main.tf — the lock table
resource "aws_dynamodb_table" "locks" {
name = "ecomarket-tfstate-locks"
# On demand: at this volume, the cost is pennies a month.
billing_mode = "PAY_PER_REQUEST"
# The name "LockID" is NOT configurable: Terraform expects exactly that.
hash_key = "LockID"
attribute {
name = "LockID"
type = "S" # S = String
}
# Point-in-time recovery: cheap and useful in audits.
point_in_time_recovery { enabled = true }
lifecycle {
# Deleting this table leaves EVERY state without a lock.
prevent_destroy = true
}
}Mutual exclusion is achieved with a PutItem conditioned on attribute_not_exists(LockID): if the item is already there, the write fails and Terraform knows somebody else holds the lock. The same table serves every state in the organisation, because the LockID includes the full path of the state object.
Why it is no longer mandatory: with use_lockfile you lose a resource, a permission, a dependency between services and a cost. If your version estate allows it, migrate. What you must not do is have half the staff on use_lockfile and the other half on DynamoDB over the same state: they would be two different locks on the same door, and each one would let through whoever is not using it.
5.3. Azure Blob and GCS
# Azure: locking through the blob's LEASE. Nothing to configure.
terraform {
backend "azurerm" {
resource_group_name = "ecomarket-tfstate-rg"
storage_account_name = "ecomarkettfstate"
container_name = "tfstate"
key = "ecomarket/dev/app/terraform.tfstate"
use_azuread_auth = true
}
}Azure's lease has an interesting property: it expires. Terraform renews it while it operates, so a dead process leaves a lock that releases itself when it expires, rather than staying forever. It is the most useful practical difference from object-based mechanisms.
# GCS: native locking through a conditional write on the generation.
terraform {
backend "gcs" {
bucket = "ecomarket-tfstate"
prefix = "ecomarket/dev/app"
}
}GCS creates a default.tflock object next to the state and writes it with a precondition on the generation number. The permission needed is roles/storage.objectAdmin over the prefix, because the lock object has to be deletable.
- The lock file and the "Error acquiring the state lock" message
6.1. What gets written
With the local backend you can watch it live. In one terminal, launch an EcoMarket apply and leave it waiting at the confirmation prompt; in another, look at the directory:
$ ls -a
. .. .terraform .terraform.lock.hcl .terraform.tfstate.lock.info main.tf terraform.tfstate
$ cat .terraform.tfstate.lock.info | jq{
"ID": "a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47",
"Operation": "OperationTypeApply",
"Info": "",
"Who": "alice@alice-laptop",
"Version": "1.9.8",
"Created": "2026-09-22T10:15:42.183746Z",
"Path": "terraform.tfstate"
}| Field | What it means | What it is useful for |
|---|---|---|
ID |
The lock's UUID | It is the argument to force-unlock. Without it you cannot release |
Operation |
OperationTypePlan, OperationTypeApply, OperationTypeInvalid... |
Knowing whether the holder is just looking or actually changing things |
Info |
Free text | Empty almost always; some CI systems fill it in |
Who |
user@machine |
The person you have to ask before forcing anything |
Version |
The Terraform version that acquired it | Spots anyone running a binary different from the team's |
Created |
UTC timestamp | Lets you work out how long it has been locked: 3 minutes is normal, 3 hours is not |
Path |
The state's path or key | Confirms it is your state and not another one |
In S3 with use_lockfile, the content is the same JSON inside the .tflock object. In DynamoDB, the item has a LockID with the object's path and an Info attribute holding this JSON.
6.2. The error, field by field
When Luke tries to apply while Alice holds the lock:
╷ │ Error: Error acquiring the state lock │ │ Error message: operation error S3: PutObject, https response error │ StatusCode: 412, api error PreconditionFailed: At least one of the │ pre-conditions you specified did not hold │ Lock Info: │ ID: a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47 │ Path: ecomarket/dev/app/terraform.tfstate │ Operation: OperationTypeApply │ Who: alice@alice-laptop │ Version: 1.9.8 │ Created: 2026-09-22 10:15:42.183746 +0000 UTC │ Info: │ │ Terraform acquires a state lock to protect the state from being written │ by multiple users at the same time. Please resolve the issue above and try │ again. For any conflicting operations that may be in progress, it may be │ appropriate to unlock the state. ╵
How to read it, from the top down:
Error messageis the backend's error, not Terraform's.PreconditionFailed(HTTP 412) means exactly that the.tflockobject already existed: the conditional write did its job. With DynamoDB you would seeConditionalCheckFailedException.Who: alice@alice-laptopis the most valuable information in the whole message. The right action is not a command: it is messaging Alice.Operation: OperationTypeApplytells you there is a change in flight. If it saidOperationTypePlanand were ten seconds old, waiting would be enough.Createdgives you the age. Compare it with the current time: that separates "they are working" from "this got stuck".IDis what you would need forforce-unlock, and it appears here precisely so you do not have to go looking for it. Its appearing does not mean you should use it.
The default answer to this error is to wait. A normal apply takes anything from seconds to a few minutes. Only if the age does not match any live operation should forcing even be considered.
terraform force-unlock: when, how and with which checklist
terraform force-unlock: when, how and with which checklistDo you really want to force-unlock? Terraform will remove the lock on the remote state. This will allow local Terraform commands to modify this state, even though it may still be in use. Only 'yes' will be accepted to confirm. Enter a value: yes Terraform state has been successfully unlocked!
What it does exactly: it deletes the lock marker. Nothing else. It does not cancel the process that created it, it reverts nothing, it does not check whether there is an apply in flight. If the lock was real, there are now two processes writing the same state: exactly the race condition of section 1, but brought about by hand.
The mandatory pre-flight checklist
Before running force-unlock against an EcoMarket state, answer these five questions in writing in the team channel:
| # | Question | How to check it |
|---|---|---|
| 1 | Who is named in Who, and have I asked them? |
A direct message. If they do not reply, escalate |
| 2 | Is there a CI job running against this state? | The pipeline dashboard: look for active runs |
| 3 | How long has it been locked? | Created against the current time. Under 15 min: almost certainly alive |
| 4 | Does the process that took it still exist? | On the originating machine: ps aux | grep terraform |
| 5 | Do I have a copy of the state in case this goes badly? | terraform state pull > copy.json, or a version from the bucket |
Situations in which forcing is legitimate:
- A CI runner was cancelled or its machine was shut down mid-operation.
- Somebody killed the process with
kill -9or closed their laptop, and has confirmed it. - The lock has been there for hours and
Whocorresponds to a machine that no longer exists (an ephemeral runner).
Situations in which it is not:
- "I am in a hurry and nobody is answering."
- The lock is three minutes old.
- You do not know what operation was in progress.
After forcing, always:
If the interrupted apply had created resources before dying, Terraform will have saved them (remember: the state is written after each resource). If it died just as it was writing, there may be real resources the state does not know about: in that case, terraform plan -refresh-only and, if necessary, import. The complete diagnostic procedure is in State Management Issues.
-lock=false and -lock-timeout
-lock=false and -lock-timeout8.1. -lock-timeout: the option you actually want
Terraform retries periodically until the deadline runs out. It is the right solution to contention in a pipeline: rather than the job failing because another job was applying, it queues up.
Sensible values for EcoMarket:
| Context | Value | Reason |
|---|---|---|
| Interactive local use | No flag (0s) | You want to find out straight away that somebody is there |
plan in CI for a PR |
-lock-timeout=2m |
Plans are short; waiting a little avoids noise |
apply in CI on the main branch |
-lock-timeout=10m |
Absorbs a queue of deployments without failing |
| A scheduled nightly apply | -lock-timeout=30m |
Nobody is waiting; better to wait than to fail |
8.2. -lock=false: the one you almost never want
$ terraform plan -lock=false # does not acquire a lock
$ terraform apply -lock=false # GENUINELY DANGEROUS-lock=false disables locking: it neither acquires nor checks it. With apply, you are voluntarily giving up the only protection against state corruption.
| Use | Acceptable? | Comment |
|---|---|---|
A read-only plan on a backend that does not support locking |
Yes | There is no alternative |
A plan in a personal test environment |
Acceptable | The risk is yours and it is small |
Any apply in staging or prod |
No | It is the direct route to the race condition |
| "To get past an orphaned lock" | No | That is what force-unlock is for, which at least leaves a trace and asks for confirmation |
| As a fixed value in the pipeline | No | It is the most common cause of corrupted states in teams that "had locking" |
The classic anti-pattern: somebody adds -lock=false to the pipeline on a day when there was an orphaned lock, the pipeline works, and the flag stays there forever. Months later the state gets corrupted and nobody understands why, because "we do have locking configured". Add a check in code review: -lock=false next to an apply is automatic grounds for rejecting the PR.
- Orphaned locks in CI and how to prevent them
The most common scenario: EcoMarket's pipeline runs terraform apply on staging, somebody cancels the job from the interface, the orchestrator sends SIGKILL to the container and the process dies without ever releasing. The lock stays, and the next deployment — somebody else's, half an hour later — fails with a Who that corresponds to a runner that no longer exists.
sequenceDiagram
participant CI as CI runner
participant B as Locking backend
participant D as Next deployment
CI->>B: acquires lock (ID=a3f1...)
Note over CI: job cancelled → SIGKILL
CI--xB: does NOT release
D->>B: tries to acquire
B-->>D: Error acquiring the state lock<br/>Who: runner-7f3a@ci (no longer exists)
Note over D: orphaned lock:<br/>deployments halted
Prevention, in order of effectiveness:
- Graceful cancellation. Configure the runner to send
SIGINTand grant a grace period before theSIGKILL. Terraform treats the firstSIGINTas "finish what you are doing and exit cleanly", and that includes releasing the lock. - A job timeout longer than the operation. A 10-minute job timeout on an
applythat takes 12 guarantees periodic orphaned locks. -lock-timeoutinstead of parallel runs. Configure the pipeline so there are never two simultaneous runs against the same environment; most CI systems have concurrency groups for this.- A conditional cleanup step. An "always runs" step that, if the
applywas cancelled, records the lock'sIDand notifies the team channel. That it notifies, not that it runsforce-unlockautomatically: an automaticforce-unlockis the worst of all worlds, because it removes the protection exactly when there may be a live process. - States separated per environment. An orphaned lock in
devmust not stop anyone deploying toprod.
The concrete integration with Jenkins, GitHub Actions and Atlantis — concurrency groups and cancellation handling included — is the content of module 8.
- Team good practices
| Practice | Why |
|---|---|
| A backend with locking from day one | Adding it after an incident is learning the expensive way |
| States separated by environment and component | It reduces contention and the blast radius of an orphaned lock |
-lock-timeout in CI, never -lock=false |
Queueing is fine; giving up the lock is not |
force-unlock always with a checklist and a notice in the channel |
It leaves a record of who forced it and why |
Banning -lock=false with apply in code review |
A grep in the pipeline catches it before it takes root |
Applying only from CI in staging and prod |
A single source of writes brings concurrency down to almost zero |
Announcing a long prod apply in the channel beforehand |
The lock explains the "why", but people appreciate the "how long" |
| Recording who has locked on a visible dashboard | In large teams, knowing who is deploying saves half a dozen messages |
The most important is the second to last combined with the sixth: in a team that deploys prod only from the pipeline and with concurrency limited to one, locking stops being a source of friction and becomes what it should be, a safety net you hardly ever notice.
Common Mistakes and Tips
- Reaching for
force-unlockas your first reflex when the error appears. The message includesWhoprecisely so that you ask before forcing. - Putting
-lock=falsein the pipeline "temporarily". It is never temporary, and one day it corrupts the state. - Believing that locking protects you from manual changes in the console. It does not: it only serialises Terraform operations. Against the console, use permissions.
- A
dynamodb_tablethat does not exist or has the wrong key. The partition key must be called exactlyLockIDand be of typeS. With any other name, theinitfails with an unclear error. - Mixing
use_lockfileanddynamodb_tableacross people in the same team. Two different locks on the same door: each one lets through whoever is not using it. Unify the Terraform version with.terraform-versionand settle on one of the two. - Granting delete permission over the whole state prefix so the
.tflockworks. Grants3:DeleteObjectonly over*.tflock. - Killing Terraform with
kill -9. UseCtrl+Conce and wait: Terraform finishes the operation in flight and releases. The secondCtrl+Cforces the exit and leaves the lock behind. - Tip: if you work with the
localbackend, launch anapplyand watch.terraform.tfstate.lock.infofrom another terminal. Seeing the file appear and disappear fixes the concept better than any explanation. - Tip: keep in the team runbook the exact command for listing active locks on your backend (
aws s3 lsfor the.tflockfiles, or ascanof the DynamoDB table). During an incident is no time to improvise it. - Tip: before a
force-unlock, runterraform state pull > copy.json. If the outcome is bad, you will have somewhere to start from.
Exercises
Exercises 1 and 2 are runnable with the local backend, which implements locking with the same .tfstate.lock.info file and the same error message as the remote backends.
Exercise 1: watching a lock live
- In a directory with EcoMarket's configuration (the
localandrandomproviders), add atime_sleepor, more simply, runterraform applywithout-auto-approveand leave it waiting at the confirmation prompt. - In another terminal, in the same directory, list the hidden files and show the contents of
.terraform.tfstate.lock.infowithjq. - Identify the file's six fields and explain what each one is for.
- Try running
terraform planfrom the second terminal. Copy the error and locate theID, theWhoand theCreatedin it. - Answer "no" in the first terminal and check what happens to the lock file.
Exercise 2: an orphaned lock and its release
- Provoke a lock as in the previous exercise and, this time, kill the process with
kill -9from another terminal. - Check that
.terraform.tfstate.lock.infois still there. - Run
terraform planand note down the error. - Before releasing, walk through the five-point checklist in section 7 out loud and justify why forcing is legitimate in this case.
- Release with
terraform force-unlock <ID>and verify withterraform planthat the state is still consistent. - Repeat the experiment using
-lock-timeout=30sfrom the second terminal with the lock alive (without killing the process). What message does it show and how does it differ from the error in point 3?
Exercise 3: designing EcoMarket's concurrency policy
On paper, draft the following for the ecomarket-infra repository:
- A table stating, for each of the three environments, who may run
apply, from where and with what-lock-timeout. - The written
force-unlockprocedure the team would follow, with the checklist and who gets notified (use the contact[email protected]). - Two automatic controls you would add to the pipeline so that
-lock=falsenever appears next to anapply. - A justification of why separating the
networkandappstates reduces locking, with a concrete EcoMarket example.
Solutions
Solution 1:
# Terminal 1
$ terraform apply
# ... plan ...
Enter a value: # <-- leave it here
# Terminal 2
$ ls -a | grep lock
.terraform.lock.hcl
.terraform.tfstate.lock.info
$ jq . .terraform.tfstate.lock.info
{
"ID": "a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47",
"Operation": "OperationTypeApply",
"Info": "",
"Who": "alice@alice-laptop",
"Version": "1.9.8",
"Created": "2026-09-22T10:15:42.183746Z",
"Path": "terraform.tfstate"
}| Field | What it is for |
|---|---|
ID |
The argument to force-unlock |
Operation |
Telling a plan (short) from an apply (may take a while) |
Info |
Free text, normally empty |
Who |
Who to ask before forcing anything |
Version |
Spotting anyone running a different binary |
Created |
Working out the lock's age |
Path |
Confirming it is the state you think it is |
# Point 4
$ terraform plan
╷
│ Error: Error acquiring the state lock
│ Lock Info:
│ ID: a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
│ Who: alice@alice-laptop
│ Created: 2026-09-22 10:15:42.183746 +0000 UTC
╵Point 5: on answering no, Terraform cancels the operation cleanly and releases the lock; the .terraform.tfstate.lock.info file disappears. A clean exit always releases.
Solution 2:
# Terminal 2
$ pkill -9 -f 'terraform apply'
$ ls -a | grep tfstate.lock
.terraform.tfstate.lock.info # still there: SIGKILL leaves no chance to release
$ terraform plan
│ Error: Error acquiring the state lock
│ ID: a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
│ Who: alice@alice-laptopPoint 4: forcing is legitimate because (1) you know who took it — you did, (2) no CI job is involved, (3) you know the exact age, (4) you have checked with ps aux | grep terraform that the process no longer exists, and (5) you can copy the state before acting.
$ terraform state pull > /tmp/copy-before-forcing.json
$ terraform force-unlock a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
Enter a value: yes
Terraform state has been successfully unlocked!
$ terraform plan
No changes. Your infrastructure matches the configuration.Point 6, with the lock alive and -lock-timeout:
The difference is substantial: rather than failing immediately, Terraform retries for the stated period. If the lock is released before it expires, the operation carries on as normal; if not, then it does show the same error as in point 3. It is exactly the behaviour you want in a pipeline: queue rather than fail.
Solution 3:
| Environment | Who applies | From where | -lock-timeout |
|---|---|---|---|
dev |
Anyone on the team | Local or CI | 2m in CI, no flag locally |
staging |
The pipeline only | CI, main branch | 10m |
prod |
The pipeline only, with manual approval | CI, concurrency limited to 1 | 30m |
EcoMarket's force-unlock procedure:
- Take the
ID,Who,OperationandCreatedfrom the error. - Contact the person or team in
Who. If it is a runner, check on the CI dashboard that the job is no longer alive. - Check the age: under 15 minutes, wait unless there is explicit confirmation.
- Copy the state:
terraform state pull > copy-$(date +%s).json. - Post in the team channel, copying
[email protected]: affected state,ID,Who, age and reason. - Run
terraform force-unlock <ID>. - Verify with
terraform planand, if anything unexpected appears, follow the procedure in State Management Issues.
Automatic controls:
# 1. In the pipeline, before planning: reject the forbidden flag.
if grep -rn -- '-lock=false' .github/ scripts/ | grep -q 'apply'; then
echo "ERROR: -lock=false next to an apply. Forbidden by policy."
exit 1
fi# 2. Concurrency group: never two runs against the same environment.
concurrency:
group: terraform-${{ inputs.environment }}
cancel-in-progress: false # queue, do NOT cancel: cancelling leaves orphansPoint 4: separating network and app into different states means two independent locks. A concrete example: the platform team applies a subnet change in staging's infra/network, an operation that takes six minutes; meanwhile, the application team deploys a new version with infra/app. With a single state, the second would wait six minutes or fail; with separate states, it never even notices. And if the network apply leaves an orphaned lock, application deployments keep working.
Conclusion
Locking is the piece that turns a shared state into a safe state:
- Without locking, the sequence read → decide → write is not atomic, and two simultaneous
applyruns produce orphaned resources, overwritten states and, in the worst case, corrupt JSON. - Terraform acquires the lock through a conditional write in the backend — a
.tflockobject, a DynamoDB item, a blob lease, a GCS generation — holds it for the duration of the operation and releases it at the end. - They lock:
apply,destroy,import, thestatecommands that write, andplantoo; they do not lock:state list,show,output,validateorfmt. - Almost every backend supports locking; the one to watch is
http, where it is optional. In S3,use_lockfileis the modern option and DynamoDB keyed onLockIDthe classic one, still very widespread; never mix the two mechanisms over the same state. - The lock file contains
ID,Operation,Who,VersionandCreated: theIDis whatforce-unlockneeds, butWhoandCreatedare what you should really look at first. force-unlockcancels nothing: it only deletes the marker. It is run with a checklist, with a notice to the team and with a copy of the state taken beforehand.-lock-timeoutqueues and is the right answer to contention in CI;-lock=falsegives up the protection and has no place next to anapply.- Orphaned locks almost always come from cancelled CI runners: they are prevented with graceful cancellation, coherent timeouts, limited concurrency and states separated per environment.
With this, EcoMarket's state is where it should be and protected from concurrency. One last debt remains in the module, and it is a promise that has been dragging on since module 2: refactoring the code — renaming a resource, moving it into a module, migrating from count to for_each — still means, as things stand, running terraform state mv commands by hand that nobody sees in the PR and that your colleague will never run. In Declarative Refactoring you close the module with the moved and removed blocks, which turn those surgical operations into reviewable code.
