Terraform and OpenTofu state is the record that connects configuration to real infrastructure. This guide explains how to import existing resources, move or rename addresses, remove stale objects, handle drift, and recover safely without turning a refactor into an unintended production rebuild.
Overview
State operations change how an infrastructure tool identifies and manages resources. They do not usually change the cloud resource directly; instead, they change the relationship between configuration, state, and the provider's remote object. That distinction is the foundation of safe work.
Before any operation, confirm the working directory, workspace or project context, backend configuration, provider versions, and credentials. Run terraform version or tofu version, then inspect the intended state with terraform state list or the OpenTofu equivalent. Never assume that a familiar resource address points to the state you intend to change.
Use this decision guide:
| Situation | Preferred operation | Primary verification |
|---|---|---|
| An existing object is not tracked | import or an import block | Plan shows no replacement or unexpected changes |
| A resource address changes during refactoring | state mv or a matching moved block | Plan shows the old address removed and the new address retained |
| An object should no longer be managed | state rm, only after confirming ownership | Remote infrastructure remains intentionally unmanaged |
| State is damaged or a change was interrupted | Backend version or state backup recovery | State can be read and the plan matches expectations |
| Provider data differs from state | Refresh through a reviewed plan, then remediate deliberately | Drift is understood before applying changes |
For a broader module design context, pair these procedures with the Terraform Module Design Guide. Clear module boundaries and stable naming reduce the number of risky state moves later.
Protect the starting point
Take a backup before manual state work. For a local state file, copy it to a protected location. For a remote backend, identify how state versions, locking, and recovery are handled. A command such as terraform state pull > state-before-change.json can provide a readable snapshot, but it is not a substitute for the backend's own version history or access controls.
Use a separate change record that includes the old address, the new address, the reason, the operator, the plan output, and the recovery path. Treat state as sensitive: it can contain resource identifiers and, depending on configuration and provider behavior, sensitive values.
Maintenance cycle
State management should be maintained like a release process rather than treated as an emergency-only skill. On a regular review cycle, check the following:
- Tool and provider compatibility: review Terraform or OpenTofu versions, provider constraints, and backend behavior before upgrading. Test state commands in a non-production workspace or a copied state where practical.
- Backend recovery: verify that authorized operators know how locking, state versions, snapshots, and restore procedures work. Document whether recovery is automatic, manual, or dependent on the storage platform.
- Refactor hygiene: inspect pull requests for renamed resources, moved modules, removed instances, and changes to
for_eachkeys. Require an explicit migration mechanism instead of relying on a lucky plan. - Drift review: investigate recurring out-of-band changes. A one-time correction may be reasonable; repeated drift often indicates unclear ownership, a missing module input, or a process that bypasses the platform.
- Runbook testing: rehearse import, move, lock recovery, and backup restoration in a safe environment. A recovery command that has never been tested is an assumption, not a runbook.
For production delivery, connect state changes to the same review controls used for other infrastructure changes. A CI job should initialize the intended backend, create a plan, preserve the plan output, and prevent an apply against an unexpected workspace or branch. The Terraform State Recovery Runbook provides a useful companion for documenting locking, drift, and backup procedures.
Signals that require updates
Refresh this guide and your local runbooks when command syntax, backend behavior, or team workflows change. Important signals include:
- A Terraform or OpenTofu release changes state subcommands, import workflows, moved-block behavior, locking options, or state serialization.
- A provider upgrade changes resource identity, import identifiers, replacement behavior, or the fields returned during refresh.
- The team changes from local state to a remote backend, or changes the backend's locking and versioning mechanism.
- Modules begin using
for_each, nested modules, or dynamic resource addresses in ways that alter how instances are identified. - A plan reports unexpected replacements after a harmless-looking rename, provider upgrade, or configuration normalization.
- An incident reveals that operators cannot identify the correct workspace, access the state backup, or restore a known-good version.
- Search intent shifts toward newer import workflows, Terraform and OpenTofu differences, or a particular backend's recovery procedure.
Do not copy commands between Terraform and OpenTofu without checking the installed version and documentation for that environment. Their state concepts and many command patterns are similar, but release behavior, supported features, and provider or backend compatibility can differ.
Common issues
Importing an existing resource
Import is appropriate when infrastructure already exists but is absent from state. First write a configuration address for the resource and determine the provider-specific import identifier. Then import the object into that address:
terraform import 'module.network.aws_vpc.main' vpc-0123456789abcdef0Use the equivalent tofu import command when operating with OpenTofu. Some workflows support declarative import blocks, which can make imports reviewable in version control. Whichever method you use, import is only the first step. Run a plan and reconcile configuration with the attributes returned by the provider. An import that succeeds technically can still produce a plan that proposes changes, replacement, or deletion.
Moving or renaming an address
If the remote object should remain the same but its address changes, use a state move or a configuration-level moved block. For a direct move:
terraform state mv 'aws_instance.web' 'module.compute.aws_instance.web'For a refactor committed to a shared module, a moved block can communicate the old and new addresses to every environment that consumes the configuration. Confirm the exact instance keys when moving resources managed with count or for_each. A missing key or incorrect module path can cause Terraform or OpenTofu to see a new object and plan a create or destroy.
Removing stale objects
state rm removes an address from state; it does not normally destroy the remote object. That makes it useful when ownership is intentionally transferred or an object was retired outside the tool. It is also dangerous: the next plan may attempt to create a replacement, and the unmanaged object may remain exposed or accumulate cost. Record who owns the object after removal and confirm the result with a plan.
Handling locks
Remote backends commonly use a lock to prevent concurrent state writes. A lock error is a coordination problem first, not a reason to force unlock immediately. Check whether another plan or apply is active, identify the lock holder if the backend exposes that information, and wait for a normal release when possible. Use force-unlock only after verifying that no operation is running and only with the lock identifier requested by the tool. An incorrect force-unlock can permit concurrent writes and corrupt the state relationship.
Recovering a damaged state
Stop automation before recovery. Preserve the current state, identify the last known-good backend version or backup, and record the incident timeline. Restore through the backend's supported versioning mechanism where possible rather than editing JSON by hand. After recovery, run a read-only inspection and a plan with the correct variables and provider credentials. If the plan contains broad changes, stop and investigate; a successful state restore does not guarantee that configuration and remote infrastructure are aligned.
Provider-specific import IDs, eventual consistency, immutable fields, and API permissions can all affect the result. Validate one resource class at a time in a non-production environment when the provider's behavior is unclear.
When to revisit
Revisit this article and your operational runbook on a scheduled review cycle, after a tool or backend upgrade, and whenever a state-related incident occurs. Also review it before a major module refactor, migration between Terraform and OpenTofu, backend migration, adoption of a new provider, or large-scale import project.
Use this practical checklist before applying any state operation:
- Confirm the binary, working directory, backend, workspace, account, and region.
- Take a state snapshot and confirm where the authoritative backup or version history lives.
- Write down the old and new resource addresses, or the exact import identifier.
- Acquire the normal state lock and stop if another operation is active.
- Run the smallest supported state command; avoid hand-editing state unless an approved recovery procedure explicitly requires it.
- Run a plan with the same variables and provider configuration used by CI or production.
- Review every create, destroy, replace, and sensitive change with a second operator.
- Apply only after the plan matches the intended ownership change, then record the result.
State operations become safer when they are predictable, reviewable, and rehearsed. Keep command examples aligned with the versions your team actually runs, link backend-specific recovery steps from the runbook, and treat every surprising plan as a signal to pause rather than an invitation to apply.