Three Views Can Disagree for Different Reasons
A library keeps three records of the same collection. The acquisition list says what the library intends to hold. The stocktake sheet says what a librarian counted at the last audit. The shelves say what is actually there this morning. Most days the three agree. When they do not, the interesting question is not "which record is wrong" but "which record moved, and who moved it".
Terraform keeps the same three views. The configuration in Git is the acquisition list: a reviewed commit that describes what the next apply would produce. The state snapshot is the stocktake sheet: the provider identifiers and attribute values recorded at the last write. The remote objects are the shelves: whatever the provider's API returns when Terraform asks now. A plan reads all three, but not in the order people assume. It refreshes the snapshot from the API first, and only then compares the refreshed snapshot with the configuration.
That order matters. By the time a plan prints actions, the snapshot has already been overwritten with reality, so the diff is configuration versus remote. It cannot tell you whether the difference came from an unapplied commit or an unreviewed console change. Git history and the refresh note are what separate the two origins.
Three pairwise comparisons do the separating:
- Configuration versus snapshot, before refresh. A difference here means an approved code change has not been applied yet. That is a pending change, an ordinary part of delivery, not drift.
- Snapshot versus remote. A difference here means the world moved after the last apply. Terraform reports it as an out-of-band change, meaning any change to a managed object that did not pass through this root's reviewed apply.
- Configuration versus remote. This is the net gap the next apply proposes to close. It is what most people call drift, and it is the only one of the three that a plan can show you directly.
Figure 1 traces how the three views meet inside a plan, and where the two origins of a difference get lost.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
CFG["Configuration
the reviewed commit"]
STA["State snapshot
the last recorded observation"]
REM["Remote objects
what the provider reports now"]
REF["Refresh: the provider reads each managed instance"]
NOTE["Plan note: objects have changed outside Terraform"]
REC["Refreshed snapshot: the record now equals reality"]
CMP["Compare the refreshed record with the configuration"]
Q{"Any difference left?"}
CLEAN["No changes: the three views agree"]
DEC["A proposed action, with two possible origins"]
GIT["Git history: is HEAD the commit that was applied?"]
PEND["Pending change
code moved, nothing applied yet"]
OOB["Out-of-band change
the object moved outside the workflow"]
RO["Refresh-only records it and touches nothing else"]
APPLY["The ordinary reviewed apply"]
STA --> REF
REF --> NOTE
REF --> REM
REM --> REC
NOTE --> REC
REC --> CMP
CFG --> CMP
CMP --> Q
Q -->|"no"| CLEAN
Q -->|"yes"| DEC
DEC --> PEND
DEC --> OOB
GIT -.->|"answers the pending branch"| PEND
OOB --> RO
PEND --> APPLY
RO -->|"re-plan"| CLEAN
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Q,CMP primary;
class CFG,STA,REM,REF,NOTE,REC,DEC,GIT,PEND,APPLY secondary;
class CLEAN ok;
class OOB,RO warn;
HCP Terraform's documentation draws a useful line inside the out-of-band case. Configuration drift is an external change that invalidates the configuration, so the configuration must be restored or rewritten. State drift is an external change that does not invalidate it, so only the record is stale. The distinction is operational: with no unapplied change in flight, run a refresh-only plan and apply it, then a normal plan. A clean second plan means state drift; proposed changes mean configuration drift.
Figure 2 sets the four combinations out as a small truth table, with A for configuration, B for snapshot and C for remote reality.
The table is a diagnostic, not a taxonomy. Read the two comparisons in order: first ask whether the code has moved since the last apply, then ask whether the world has moved. The verdict names the command family, and the next sections take them one at a time.
Detect Drift with a Normal Plan and Read the Context
There is no special drift command in Terraform Core. A normal terraform plan refreshes every managed instance by calling the provider's read function, comparing the returned object with the recorded one, and then comparing the refreshed result with configuration. That first comparison is the drift detector; everything after it is a proposal built on top.
The detector's report has a fixed shape. When something moved, the plan prints a section headed "Objects have changed outside of Terraform", one block per affected address, with the changed attributes and their old values. If the new reality still matches your configuration, the plan then proposes nothing, and you have state drift only. If the new reality contradicts the configuration, the same note is followed by actions that would undo it. Both halves of the output matter, and they are easy to read as one. A note without actions is a recording problem. A note with actions is a decision.
Exit codes are where automation usually gets this wrong. A plain plan succeeds with 0 whether or not it found changes; a failed run stops at 1. The detailed flag adds a third value that means "work", not "drift".
| Exit | Plain plan | With -detailed-exitcode | Read it as |
|---|---|---|---|
0 | Success, changes or not | Empty diff | Nothing to propose for this commit |
1 | Error | Error | Credentials, lock, provider or syntax |
2 | — | Non-empty diff | Work exists: pending change, drift or a noisy version bump |
Read the code as a statement about the plan, not the estate. A commit that has not been applied also exits 2, and so does a version bump that changes a dozen attributes; alerting on that value alone produces a queue of true statements nobody can act on.
Three signals disambiguate. The refresh note says whether the object moved. The saved plan's resource_drift array lists the addresses whose refresh found a difference, separate from resource_changes, which lists what the plan proposes. Git tells you whether the commit being planned is the commit that was last applied. Read together, they answer the two questions the exit code cannot: did the world move, and did the code move.
Scheduling makes the detector continuous. Pick a cadence from change rate and blast radius: hourly for a root that fronts payment traffic, daily for a shared network root, weekly for a sandbox. Run one job per root, with the same state backend and the same read access the apply uses. A scheduled plan running with a narrower role is worse than no plan at all, because a permission gap on one service makes the provider report every object in that service as deleted. The job then opens a critical ticket about infrastructure that is perfectly healthy.
Ownership decides whether any of this works. A root is the unit that owns one state, one lock and one set of approvers, so it is also the unit that owns drift: every root needs a named team, a channel and a tier. Route the drift report to the owner, not to a shared platform alias, and include the address, the attribute that moved, the commit and the time of first observation. Tier the response: identity, network and public-access resources are same-day; compute and storage corrections are next-business-day; tag and description churn is batch work. Without that routing, a drift job is a log file with extra steps.
HCP Terraform packages the same mechanics as health assessments. Drift detection runs a speculative plan on a schedule, marks workspaces with a health warning, and reports the number of drifted resources, with notifications configured per workspace. It requires remote or agent execution, a successful latest run, and Terraform 0.15.4 or later for drift alone, or 1.3.0 or later for drift plus continuous validation; the feature is limited to the Standard and Premium editions. Confirm the edition and workspace settings before promising it to a team.
Figure 3 follows a scheduled run from exit code to owner, including the branches where a green or red result is not about drift at all.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
SCH["Scheduled job: one root, apply-level read access"] --> PLAN["terraform plan -detailed-exitcode -out=tfplan"]
PLAN --> RC{"Exit code"}
RC -->|"0"| ZERO["No changes for this commit"]
RC -->|"1"| ERR["Error: credentials, lock, provider or syntax"]
RC -->|"2"| JSON["Read the drift section, not the summary"]
JSON --> D{"Does resource_drift list any address?"}
D -->|"no"| CONF["Configuration-only change: ordinary review"]
D -->|"yes"| OWN["Route to the root owner with address, attribute, commit and time"]
OWN --> TRIAGE{"Was the change intentional?"}
TRIAGE -->|"yes"| ADOPT["Adopt: commit the new value"]
TRIAGE -->|"no"| REST["Restore: apply the reviewed plan"]
TRIAGE -->|"unknown"| INVEST["Incident: read the provider audit log first"]
ERR --> AUTH["A read gap looks like deletion: fix access before believing the plan"]
ZERO --> PROVE["Record: commit, timestamp, empty drift set"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class RC,D,TRIAGE primary;
class SCH,PLAN,JSON,OWN,CONF,REST,ADOPT secondary;
class ZERO,PROVE ok;
class ERR,AUTH,INVEST danger;
The failure branches carry most of the operational value. "Exit 1" is a provider or access problem until proven otherwise, and the first move is to reproduce the plan locally with the same role. "Exit 2 without a drift entry" is a code change in flight, which belongs in code review, not in an incident channel. "Exit 2 with a drift entry" is the only branch that needs a decision, and it needs a person who owns the resource.
Refresh-Only Updates Records, Not Desired Configuration
A refresh-only plan updates the state file and root output values to match remote objects. It never edits your .tf files and never calls a provider's create, update or delete operation: it calls read, writes the result into state, and stops. That narrowness lets you record reality without blessing it in code.
The procedure is three moves: plan the record update, apply that saved plan, then re-plan to classify what remains.
The deprecated refresh writes without review
terraform refresh is the same state update with auto-approve. If a provider is misconfigured or a credential has expired, it is told that every object is gone and removes every tracked address without asking. Nothing in the cloud is deleted, but the root's ownership record is wiped, and the next apply either creates a second copy or fails on a unique name.
Refresh-only has limits. It cannot make a resource exist, cannot grant permission, cannot repair a broken object, and cannot change what the configuration asks for. It can drop addresses when objects disappear and recompute outputs from the new values, so it deserves the same care as any other state write: a versioned backend, a named approver, and one writer at a time.
The listing below is the lab configuration, deliberately small: one resource, one input, one output. The commands under it are illustrative; read your own plan output rather than expecting a transcript.
The HCL panel pins the exact CLI and provider versions used elsewhere in this series; the lab in the next section explains how far that configuration was replayed.
Choose Restore, Adopt or Transfer Ownership
Once a drift report exists, the question is not technical: the diverging value is a fact, and what remains is whose intent wins, with an owner, a rationale and a date. Three answers cover almost every case.
Restore treats configuration as the intent and the cloud as the mistake. You review a normal plan and apply it, which writes the configured values back over the drifted ones; HCP Terraform calls this overwriting drift, and the reviewed plan is the safeguard.
Restore can undo the fix that kept the service alive
Restore is the right default for accidental deletion, an unrecorded value change, a security group opened during debugging, or a script that should not have credentials. The risk is easy to miss: it also erases a deliberate fix made under pressure. If a console change kept a service alive at 02:00, applying the plan at 09:00 takes it down again.
Adopt treats the cloud as the new intent. You edit the configuration to the observed value, commit it with a reference to the incident or the provider change that caused it, and let a reviewed apply run; the object usually does not change, and the code catches up.
Adoption is a reviewed decision, not a cleanup
Adopting turns an unreviewed action into permanent intent. It is right when the change was correct, when a provider now returns a value the old schema could not express, or when a manual repair is the only surviving record of a fix. Adopting an unexplained security-group change is how a debugging shortcut becomes policy.
Transfer ownership decides the object should not belong to this root at all. The team split, the service moved to another stack, or the resource is being retired while its data must survive. In Terraform 1.7 and later, a removed block with lifecycle { destroy = false } forgets the instance and leaves the object untouched; the imperative state-remove command is its equivalent, best done with a snapshot and a second reader. Either way the new owner imports the object and proves a clean plan on their side.
Forget only with a receiving owner
Forgetting without a receiving owner is how duplicate infrastructure happens. One copy lands in a new root and one invisible copy is still billing, so name the receiver before the removed block is applied.
Before choosing, classify what changed. Three categories look alike in a terminal and behave nothing alike.
Provider-normalized values are the state-drift case. The API returns 0644 where you wrote 644, reorders a JSON policy document, lowercases an enum, adds a platform timestamp, or attaches a default tag. Nothing about your intent changed, and nothing about the object is wrong. A refresh-only apply records the normalized values and the next plan is clean. If the same normalization reappears every week, it is either a provider bug worth pinning or upgrading around, or an attribute that genuinely belongs to another system.
Deliberately ignored attributes are a contract, not a fix. lifecycle { ignore_changes = [...] } compares the attribute against the prior state and keeps whatever value is there, which means it also ignores future edits you make to that attribute in code. Use it where another system owns the value — an autoscaler writing desired capacity, a platform writing cost tags, a controller writing annotations — and document the owner next to the block. Do not use it to silence a noisy plan: the noise is the detector working, and muting it moves the discovery to an outage.
Real incidents are the third category, and they deserve the slowest response. A rule opened to the world, an instance type raised, a bucket policy relaxed, a resource that reappeared after deletion: these are not configuration hygiene problems. They are evidence. Read the provider's audit log before applying anything, because the apply destroys the state that the investigation needs, and because the change may have come from a compromised credential rather than a colleague. Restore afterwards, but restore as the last step, not the first.
A drift report that records only the attribute and the action is incomplete. Record the root, address, attribute, old and new values, first observation, commit planned, chosen action, reviewer and date. That record makes the next occurrence cheaper, and it lets an auditor see that the change was decided rather than absorbed.
Avoid Detection Shortcuts That Hide the Evidence
-refresh=false skips the read phase entirely. The plan is then computed against the snapshot as it was last written, which means it cannot see anything that happened since. It may propose an update that is already applied, miss a deletion, or compute a replacement from an attribute that no longer exists. The exit code still looks authoritative, because it describes the plan that was built from stale inputs. The flag has legitimate uses: an unavailable or rate-limiting provider, a deliberate comparison against a known snapshot, a migration rehearsal. Label the plan as unrefreshed wherever its result is consumed.
-target narrows the plan to one address and its dependencies. The documentation is blunt about it: targeting is for exceptional circumstances such as recovering from a mistake or working around a provider limitation, and routine use "can lead to undetected configuration drift and confusion about how the true state of resources relates to configuration". Everything outside the selected subgraph is neither refreshed nor compared, so a clean targeted plan proves the target and nothing else. The same warning applies to -minimal-refresh, available in the 1.17 CLI, which refreshes only instances the comparison already expects to change; unchanged resources keep old records, and the docs say so.
Combining the two is the failure mode that hurts. A pipeline adds -target to keep a large root under a time limit, then adds -refresh=false to keep the API quiet, and the badge turns green. The green badge now means "the part we looked at, judged against what we remembered, had nothing to do". That is not a drift result, and treating it as one is worse than having no check, because it produces confidence without coverage.
Figure 4 contrasts the two paths and what each can honestly claim.
Auto-apply is a second change process with no reviewer
The deeper shortcut is auto-applying whenever a drift job reports work. Convergence looks responsible, but the job applies whatever plan it built, at whatever hour it ran, against whatever commit was checked out. If the drift came from an emergency fix, auto-apply is an automated rollback of that fix; if the plan was built from an old commit, it reintroduces old intent; if the drift came from an attacker, it removes the evidence before anyone reads it. A root that genuinely needs convergence should allow automatic application only when every drifted address is on a reviewed normalization list, and open a ticket for everything else.
Reconcile a Controlled Console Change
The lab closes the loop on one harmless object: one out-of-band edit, one drift report, one action, and a plan that exits 0 for the documented reason. The point is not the file but the shape of the record you would attach to a real ticket.
Resolve one drift incident
Execution status: design-only for the pinned versions. The sequence was replayed on 5 November 2026 with Terraform 1.12.2 and hashicorp/local 2.5.2 to confirm the exit codes, the refresh-only write and the post-remediation proof. The 1.17.1 flags and semantics used below are unchanged, but treat quoted console wording as shape rather than transcript.
Prerequisites. Terraform 1.17.1, hashicorp/local 2.9.1, jq, a Git repository, and a disposable directory. No cloud account and no credentials. The provider is local, so the only cost is attention.
Minimal setup. Create main.tf from the previous listing, run the lab widget's init and apply commands, and commit the result. The baseline plan must exit clean.
| # | Do this | Expected evidence |
|---|---|---|
| 1 | Write the console text straight into hello.txt; no Terraform command runs | The file differs from the configured content |
| 2 | Run terraform plan -detailed-exitcode -input=false | Exit 2, a note that local_file.hello changed outside Terraform, and a proposed action |
| 3 | Explain the identity model: local_file derives id from the file's SHA-1 content hash | A byte change looks like a different object, so the provider reports the old object deleted |
| 4 | Save a plan with terraform plan -out=tfplan -input=false, then print the addresses in .resource_drift | local_file.hello appears in drift, separate from .resource_changes |
| 5 | Choose restore: run terraform apply tfplan, then read the first line of the file | The configured greeting is back |
| 6 | Repeat the edit, change var.greeting to the console text, plan, review, apply, re-plan | Exit 0; identical bytes, but the modification time moves |
| 7 | Write the drift record on one line or in one ticket | Root, address, attribute, old and new value, first observed, commit planned, action, reviewer, date |
| 8 | Run the final plan and save fresh JSON evidence | Exit 0; neither .resource_drift nor .resource_changes lists an address; on a clean plan the keys are often absent, not empty |
| 9 | Optional: replace the resource and output with a removed block carrying lifecycle { destroy = false }, then apply | terraform state list is empty and hello.txt still exists; the object is forgotten, not destroyed |
Expected observation. One drift entry for one address, one recorded decision, and a final plan whose empty diff is the proof. Along the way, the same remote state produced two different plans depending only on which configuration you chose.
| Signal | What it means | First move |
|---|---|---|
Exit 1 | Provider, network or syntax failure | Fix the run before believing the resources changed |
Exit 2 with an empty resource_drift | A configuration change, not drift | Send it to code review |
Empty drift list with a non-empty resource_changes after the file edit | The refresh never saw the object | Check the directory and workspace |
apply tfplan refuses the saved plan | A state write happened after the plan was saved | Re-plan; do not force it |
Cost dimensions. Zero. The file is a few dozen bytes; the provider is local; the CLI, jq and Git are already installed. The real cost is the discipline of recording the decision before running the command.
Cleanup. Remove the plan files and destroy the lab, then confirm the state list is empty and remove the working directory. Keep the drift record; it is the only durable output.
The pattern generalises without the local provider. Replace the address and the attribute, keep the four moves: detect with a normal plan, separate drift from pending work, record the decision with a named owner, and close with a plan that exits 0 for the right reason. A green plan is not proof of health unless you can say what it read.
Next in the Series
In Diagnose Slow Plans and Provider Failures Systematically, we'll explore Measure bottlenecks before changing parallelism, graph structure or refresh behavior.