Terraform State Recovery Runbook: Locking, Drift, Backups, and Safe Remediation
TerraformOpenTofuInfrastructure as CodeState ManagementDrift Detection

Terraform State Recovery Runbook: Locking, Drift, Backups, and Safe Remediation

MMidways Cloud Editorial Team
2026-11-17
7 min read

A practical Terraform state recovery runbook for locks, failed applies, drift, backups, corruption, and safe remediation.

Terraform state is the record that connects configuration to real infrastructure. When an apply fails, a lock remains, drift appears, or state seems damaged, the safest response is deliberate rather than destructive. This runbook provides a reusable Terraform state recovery checklist: identify the scenario, preserve evidence, verify backups, inspect state safely, and choose the smallest remediation that restores reliable operations.

Overview

State recovery is an incident-management task, not merely a command-line exercise. Before changing anything, pause automated plans and applies that use the affected state. Tell collaborators which workspace, project, or environment is under investigation, and record the time, failed command, run ID, backend, Terraform or OpenTofu version, provider versions, and recent configuration changes.

The first decision is whether the problem is a lock, a failed operation, drift, or possible corruption:

  • Lock: another operation may still be running, or a previous process may have ended without releasing its lock.
  • Failed apply: some resources may have changed even though the overall run failed. The state may be valid but incomplete relative to the desired configuration.
  • Drift: infrastructure changed outside the workflow, or a provider now reports a different value than the state contains.
  • Suspected corruption: state cannot be read, has unexpected structure, or no longer represents the known resources and dependencies.

Do not begin with terraform state rm, manual edits, or a forced unlock. Those actions can remove information or allow concurrent writers. First preserve the current state and establish whether a legitimate operation is still active.

For broader review controls, pair this runbook with the Infrastructure as Code Code Review Checklist and validate changes with a production release readiness checklist.

Checklist by scenario

Scenario 1: A state lock remains

  1. Confirm the workspace, account, region, and backend are correct. A lock in a different environment is not the same incident.
  2. Check the CI/CD system, terminal sessions, runners, and deployment notifications for an active plan or apply.
  3. Inspect backend-native lock information if available. Record the lock ID, owner, operation, and creation time.
  4. Ask the apparent owner to confirm whether the process is still running. If it is active, do not interrupt it unless the incident procedure requires that action.
  5. Verify that no process is writing state before considering a forced unlock.
  6. Use the documented backend or Terraform command to remove a confirmed stale lock. Treat terraform force-unlock LOCK_ID as a last resort, and obtain a second review for production state.

A force-unlock does not undo an infrastructure change and does not repair state. It only removes the coordination record. If the original process is still active, another operation can write concurrently and create a more serious recovery problem.

Scenario 2: An apply failed

  1. Save the complete error output, including the resource address and provider message.
  2. Check whether the backend accepted a new state version after the failure. Remote backends often retain version history, but retention and recovery features depend on the backend configuration.
  3. Run terraform state pull > state-after-failure.tfstate only after confirming the command targets the intended workspace. Protect the file because it can contain sensitive values.
  4. Inspect the affected resource with terraform state show ADDRESS. If the resource was created outside the expected relationship, inspect the provider and platform directly before taking action.
  5. Run a plan and read the proposed actions carefully. A failed apply may be safely recoverable with another apply, but only after understanding whether the failure was transient, configuration-related, or caused by an external change.
  6. Do not assume that a failed apply means nothing changed. Check cloud audit logs, resource inventories, and provider-specific operation status.

Scenario 3: Drift is detected

  1. Confirm that the reported difference is real and not caused by an unknown value, provider normalization, a computed field, or a changed default.
  2. Identify who or what changed the resource: a console action, another automation system, a platform controller, a provider upgrade, or a security policy.
  3. Choose an explicit outcome: adopt the real infrastructure, restore the declared configuration, or change the configuration so the new behavior is intentional.
  4. Use a refresh-only plan to inspect state changes without proposing normal configuration changes: terraform plan -refresh-only. Review the result before applying any refresh-only change.
  5. Apply the selected correction through the normal reviewed workflow. Avoid making a one-off console change that leaves the source of truth ambiguous.

Scenario 4: State may be corrupted

  1. Stop all writers and preserve the current state output, backend metadata, logs, and relevant configuration.
  2. Check whether the state can be read with terraform state pull and whether the configuration can initialize against the same backend without changing it.
  3. Compare the current state with the most recent known-good backend version or backup. Verify timestamps and workspace identity before using a backup.
  4. Restore only through the backend's supported versioning or recovery mechanism when possible. If a manual state push is unavoidable, use a copied file, require review, and document the exact source and target.
  5. After recovery, run a plan and reconcile unexpected actions one resource at a time. Escalate to the backend, provider, or platform owner if resource identity or dependency relationships are unclear.

What to double-check

State-backup verification checklist

  • Is the backend bucket, workspace, project, or state key correct?
  • Is backend versioning, snapshotting, or retention actually enabled rather than merely assumed?
  • Can an authorized operator list and retrieve earlier state versions?
  • Has the backup been tested by restoring it to an isolated location or temporary workspace?
  • Are state files protected because they may contain credentials, tokens, or other sensitive values?
  • Does the backup include a clear timestamp, commit reference, workspace name, and tool version?
  • Is the recovery procedure independent of the failed runner or deployment account?

State inspection commands

Run commands from a controlled checkout with the intended variables and backend configuration. Useful read-focused commands include:

  • terraform version to record the tool version.
  • terraform workspace show to confirm the selected workspace where workspaces are used.
  • terraform state pull to retrieve a protected copy for inspection.
  • terraform state list to review tracked addresses.
  • terraform state show ADDRESS to inspect one tracked object.
  • terraform plan -refresh-only to review differences caused by refreshed remote values.

Terraform and OpenTofu commands are similar in many workflows, but backend behavior, locking, provider support, and state-recovery features can vary by version and implementation. Confirm the command and recovery process against the tool and backend documentation used by your team.

Drift-remediation choices

FindingPreferred responseRisk to check
Intentional infrastructure changeUpdate configuration and review the resulting planChanging one resource may affect dependencies
Unapproved manual changeRestore the declared configuration through automationConfirm the manual change is not hiding an incident
Provider or platform normalizationReview provider behavior and consider a documented lifecycle ruleIgnoring a persistent difference can conceal real drift
Resource exists but is not trackedAssess whether an import is appropriateImporting the wrong object can create destructive future plans
Resource is tracked but goneConfirm deletion and decide whether recreation is intendedRecreation may replace data or change access

Common mistakes

  • Force-unlocking by default: A lock is protection against concurrent state writes. Prove it is stale first.
  • Running apply repeatedly: Repetition without reading the error and resulting plan can compound a partial failure.
  • Editing state JSON by hand: State contains relationships and metadata that are easy to damage. Prefer supported state commands or backend recovery.
  • Deleting a state entry to make a plan look clean: terraform state rm stops tracking an object; it does not remove the real resource and may cause later duplication or unmanaged infrastructure.
  • Restoring an old backup without checking the timeline: An older state can omit legitimate resources created after that version.
  • Ignoring secrets in copied state: Store diagnostic files in restricted locations, limit access, and delete them according to your security procedure.
  • Mixing workspaces or backends: A correct command against the wrong state is still an outage risk. Make the target visible in incident notes and shell prompts where practical.
  • Skipping the post-recovery plan: Recovery is incomplete until the team understands the next plan and has a controlled path to apply it.

State incidents also expose process weaknesses. Review whether CI/CD can prevent concurrent applies, whether backend recovery is documented, and whether ownership is clear. A CI/CD pipeline maintenance playbook can help establish recurring checks, while an incident postmortem template can capture improvements without assigning blame.

When to revisit

Review this runbook before seasonal planning cycles, backend migrations, major Terraform or OpenTofu upgrades, provider upgrades, workspace reorganizations, and changes to CI/CD concurrency. Revisit it after every state incident and whenever the team changes how locks, backups, permissions, or approvals work.

At least once during a planned recovery exercise, verify that an authorized operator can retrieve a known-good state version, identify the correct workspace, and produce a safe plan without touching production resources. Record the result, limitations, and owner of each unresolved action.

Practical next step: create a short incident record now with these fields: target workspace and backend, current lock status, last successful run, state-backup location, tool and provider versions, observed error, resources affected, and the next approved action. Then pause concurrent writers, preserve evidence, and proceed through the matching scenario above. That sequence turns Terraform state recovery from a rushed command into a controlled platform-engineering operation.

Related Topics

#Terraform#OpenTofu#Infrastructure as Code#State Management#Drift Detection
M

Midways Cloud Editorial Team

DevOps and Platform Engineering Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.