Terraform 26: State locking, drift, and refresh
easy⏱ 5 mincourseterraform
Locking prevents concurrent corruption
When an operation writes state, the azurerm backend takes a blob lease on the state file. A second apply that starts meanwhile fails fast with a lock error instead of racing and corrupting state. The lock is released automatically when the run finishes. This is a big reason remote backends beat local files for teams.
# A concurrent run refuses to proceed:
#
# Error: Error acquiring the state lock
# Lock Info:
# ID: 3f1c...
# Operation: OperationTypeApply
# Who: ci-runner@build-agent-7
#
# Only force it if you are SURE no run is active:
# terraform force-unlock 3f1c...
Drift and refresh
Drift is when the real resource diverges from state — someone edited it in the portal, or another tool changed it. Before planning, Terraform refreshes: it re-reads each resource from the cloud and updates state's recorded values, so the plan compares your config against current reality and proposes to reconcile the difference.
terraform refresh is deprecated — use plan/apply flags
The standalone terraform refresh command silently mutated state and is deprecated. Instead, refresh happens automatically inside plan/apply. To only reconcile drift without changing config, run terraform apply -refresh-only; to skip the refresh for speed, run terraform plan -refresh=false.
# See drift without proposing config changes:
terraform plan -refresh-only
# Accept the refreshed reality into state:
terraform apply -refresh-only
Detect the drift
Implement detectDrift(desired, actual) returning a sorted array of the keys whose values differ between the two objects (assume the same keys). The starter compares { sku: "Standard", minTls: "1.2" } against { sku: "Premium", minTls: "1.2" } and logs the result — expected ["sku"].