Terraform drift detection means asking Terraform whether real infrastructure still matches what it last applied. The built-in way is terraform plan -refresh-only -detailed-exitcode: it reads every managed resource from the cloud, reports anything changed outside Terraform, and exits with code 2 when drift exists. Schedule it, route the result to an owner, then decide per change: revert it or codify it.
That's the whole trick. The hard part isn't the command. It's that most teams run it zero times between incidents.
You know the story. Someone opened port 5432 "just for ten minutes" during a 2 a.m. incident. The ten minutes became eight months. Your Terraform still says the database is private, your architecture diagram still says it's private, and the only thing that knows the truth is AWS. That gap is drift, and it's how "we're fully IaC" quietly turns into vibes.
What Terraform drift actually is (and what it isn't)
Drift is any difference between the real object in your cloud account and the last state Terraform recorded for it. It usually comes from:
- ClickOps. Console edits during incidents, demos or "quick tests".
- Other automation. Autoscalers, security agents or a second pipeline touching the same resource.
- Provider-side changes. Defaults or computed values the platform updates on its own.
- Deletions. A resource removed by hand while state still lists it.
Two things are easy to confuse here, so let's separate them:
| Situation | Does Terraform see it? | How it shows up |
|---|---|---|
| Managed resource changed outside Terraform | Yes | Refresh-only plan lists it as changed |
| Managed resource deleted by hand | Yes | Refresh-only plan says it "has been deleted" |
Your .tf code changed but not applied | Yes | A normal plan proposes the update (that's pending change, not drift) |
| Resource created by hand, never in state | No | Nothing. Terraform has no idea it exists |
Attribute listed in ignore_changes | Hidden for updates | Changes to it aren't proposed |
That fourth row is the one that bites. HashiCorp has said it plainly for years: Terraform cannot detect drift in resources it doesn't manage. So "no drift" from Terraform means "nothing I track has changed", not "your account matches your code".
→ Compare architecture intent with deployed reality in Drift Detector
How to detect Terraform drift with terraform plan -refresh-only
Refresh-only mode has been in Terraform since v0.15.4, and it's the tool for this job. A normal plan also refreshes in memory, but it mixes drift together with your pending code changes. A refresh-only plan only answers one question: what changed outside Terraform since the last apply?
terraform init -input=false
terraform plan -refresh-only -detailed-exitcode -input=false
When something drifted, the output starts like this (from HashiCorp's refresh-only tutorial, trimmed):
Note: Objects have changed outside of Terraform
Terraform detected the following changes made outside of Terraform since the
last "terraform apply":
# aws_instance.server has been deleted
It then reminds you: "This is a refresh-only plan, so Terraform will not take any actions to undo these." Nothing in your account changes. Nothing in state changes either, because it's only a plan.
With -detailed-exitcode, the exit code tells a script what happened:
| Exit code | Meaning | What your job should do |
|---|---|---|
0 | Succeeded, no changes | Stay quiet |
1 | Error | Alert: credentials, backend or provider problem |
2 | Succeeded, there is a diff | Alert: drift found, open a ticket |
Treat exit 1 as seriously as exit 2. A drift job that has been failing on expired credentials for three weeks is worse than no job, because everyone assumes it's green.
Is terraform refresh deprecated?
Yes. The terraform refresh command page says it's deprecated and "effectively an alias" for terraform apply -refresh-only -auto-approve. The auto-approve is the problem. HashiCorp warns that with misconfigured credentials, Terraform can think every managed object was deleted and remove them all from state without asking.
Use these instead:
terraform plan -refresh-onlyto look at drift. Safe, read-only.terraform apply -refresh-onlyto accept drift into state. It shows the changes and asks for confirmation first.
Also avoid -refresh=false in any job meant to catch drift. It skips checking remote objects, so you're planning against an old record by design.
→ Explore modules, providers and dependencies in IaC Orchestration
Terraform drift detection in CI: a scheduled job that works
Running the command once is a demo. Running it every day, per workspace, with a clear owner is drift detection. Here's a minimal GitHub Actions workflow that does that for one root module:
name: terraform-drift
on:
schedule:
- cron: '30 2 * * *' # daily, 02:30 UTC
workflow_dispatch:
permissions:
contents: read
id-token: write # for OIDC to your cloud provider
jobs:
drift:
runs-on: ubuntu-latest
defaults:
run:
working-directory: infra/prod
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_wrapper: false
# Authenticate to your cloud here (e.g. an OIDC role with read-only access)
- run: terraform init -input=false
- name: Refresh-only plan
run: |
set +e
terraform plan -refresh-only -detailed-exitcode -input=false -no-color > drift.txt
rc=$?
set -e
cat drift.txt
if [ "$rc" -eq 2 ]; then echo "::error::Drift detected in infra/prod"; exit 1; fi
exit "$rc"
A few choices in there are deliberate:
terraform_wrapper: false. The setup action's wrapper script is handy for capturing output, but you want the raw Terraform exit code here, not a wrapped one.set +earound the plan. Exit code 2 isn't a crash, so the script captures it before deciding what to fail on.- Read-only credentials. A refresh-only plan only needs to read resources and state. Don't give the drift job the keys that can apply.
- One job per root module. Drift in
prod/networkand drift indev/sandboxhave different owners and different urgency. Don't lump them into one red X.
Want structured output for a ticket or chat alert? Save the plan and read it as JSON. Plan JSON has a resource_drift array listing the resources Terraform found changed outside of it:
terraform plan -refresh-only -input=false -out=drift.tfplan
terraform show -json drift.tfplan \
| jq -r '.resource_drift[]? | "\(.address): \(.change.actions | join(","))"'
That gives you one line per drifted resource address, which is a far better ticket title than "drift job failed".
Using HCP Terraform instead
If your workspaces run in HCP Terraform or Terraform Enterprise, you may not need the cron job. Health assessments run speculative plans on a schedule, show a drift summary in the workspace and send notifications per your workspace settings. The docs list some prerequisites: Terraform 0.15.4 or later for drift detection, remote or agent execution mode, and a latest run that succeeded. HashiCorp says drift detection is available in "some editions", so check which plan you're on before counting on it.
→ Turn your drift job's failure path into a runbook with the free Incident Runbook Template Builder
Detect drift between Terraform and AWS: a worked example
Let's make it concrete. Your prod VPC has a database security group managed in Terraform:
resource "aws_security_group" "db" {
name = "orders-db"
vpc_id = aws_vpc.main.id
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = aws_security_group.app.id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
During an incident, three people "help" in the console. Here's what the next morning's refresh-only plan sees:
- Someone widened the managed rule's port range. That rule is a tracked resource, so the plan flags
aws_vpc_security_group_ingress_rule.db_from_appas changed and exits 2. Caught. - Someone created a new
debug-5432security group and attached it to the database. The new group itself was never in state, so Terraform doesn't know it exists. But if the RDS instance is managed in Terraform, itsvpc_security_group_idschanged, and that attribute change shows up. You see the symptom, not the culprit. - Someone launched a "temporary" bastion host with a public IP. Nothing Terraform manages references it. The plan stays green. This is the "never in state" row from the first table, live and in person.
Same incident, three very different detection stories. That's why Terraform drift detection is necessary but not enough on its own: you also need a way to spot resources that exist in AWS but not in state. That means a cloud inventory, provider audit logs, or both. If security groups are your usual suspect, read AWS security group vs NACL for what each layer really controls.
→ See which resources are governed by IaC (and which aren't) with Cloud Inventory
Fix it: revert, accept or import
Once drift shows up, every change gets exactly one of three decisions. Make the decision explicit and write it on the ticket.
| Decision | When | How |
|---|---|---|
| Revert | The change was a mistake or a temporary hack | Run a normal terraform plan and terraform apply; Terraform puts the resource back to match code |
| Accept | The change was right and should stay | Update the .tf code to match, then confirm the plan shows no changes |
| Import | A resource was created outside Terraform and should be managed | Add an import block and bring it into state |
Two traps to avoid:
Don't "accept" by only running terraform apply -refresh-only. That updates state to match reality, but your code still says the old thing. The next normal apply will happily revert the change you just accepted. Update the code first.
Use ignore_changes sparingly. The lifecycle docs say attributes in ignore_changes are considered on create but ignored when planning updates. That's right for fields another system owns:
resource "aws_instance" "worker" {
# ...
lifecycle {
# Tags are managed by our cost-allocation agent
ignore_changes = [tags]
}
}
It's wrong as a mute button for noisy drift you haven't investigated. ignore_changes = all means Terraform never proposes updates to that resource again. Comment every entry with who owns the field. If tags are what keeps drifting, our AWS tagging strategy guide covers how to stop that at the source.
For the import path, Terraform supports import blocks, and terraform plan -generate-config-out=generated.tf can draft the matching configuration. HashiCorp's generating configuration docs still label that generation experimental, so review the file before you merge it.
import {
to = aws_vpc_security_group_ingress_rule.db_from_vpn
id = "sgr-0123456789abcdef0"
}
→ See who changed what outside code with ClickOps Detection
Terraform drift detection checklist
Copy this into your platform team's backlog:
- Every production root module has a scheduled
terraform plan -refresh-only -detailed-exitcodejob (or an HCP Terraform health assessment) - Exit code 1 alerts someone, not just exit code 2
- The drift job uses read-only cloud credentials
- Each workspace has a named owner who triages drift within an agreed time
- No drift job uses
-refresh=falseor the deprecatedterraform refresh - Every drift ticket ends as revert, accept (code updated) or import
-
ignore_changesentries are commented with the owning system - Something outside Terraform looks for resources that were never in state
- The architecture diagram gets updated when an accepted change alters topology
That last item is the one everyone skips. Accepted drift often means the architecture changed: a new path, a wider trust boundary, an extra dependency. If your diagram doesn't change too, you've just moved the drift from the cloud to the docs. Our cloud architecture review checklist has a section for exactly that.
→ Map what a Terraform module really deploys with the free Terraform Module Visualizer
Key takeaways
- The built-in check is
terraform plan -refresh-only -detailed-exitcode. Exit 0 means clean, 2 means drift, 1 means your job is broken. terraform refreshis deprecated. It auto-applies state changes. Use refresh-only plans to inspect andapply -refresh-onlyto confirm.- Terraform only sees what's in state. Resources created by hand need an inventory or audit logs to find.
- Schedule it per workspace with an owner. A drift job nobody reads is just a cron job with extra steps.
- Every drift item gets one decision: revert, accept (update code) or import.
- Keep diagrams in the loop. Accepted drift is often an architecture change in disguise. For turning Terraform into a readable picture, see Terraform graph visualization and the drift control explainer.
→ Track AWS, Azure, GCP and Kubernetes drift in one place with Drift Detector
FAQ
How do I detect drift in Terraform?
Run terraform plan -refresh-only. Terraform reads every managed object from the provider, compares it with the last recorded state and lists anything that changed outside Terraform, without proposing fixes. Add -detailed-exitcode so a script can tell a clean run (exit 0) from drift (exit 2) or an error (exit 1).
Is terraform refresh deprecated?
Yes. HashiCorp's docs mark terraform refresh as deprecated and describe it as effectively an alias for terraform apply -refresh-only -auto-approve. Use terraform plan -refresh-only to inspect drift, and terraform apply -refresh-only when you want to review and confirm the state update.
Can Terraform detect resources created outside Terraform?
No. Terraform only checks objects it already tracks in state, so a security group or bucket someone created by hand never shows up as drift. To find unmanaged resources you need a cloud inventory or provider audit logs, then bring the ones you want into code with an import block.
How often should I run Terraform drift detection?
Daily is a sensible default for production workspaces, with more frequent runs for high-risk ones such as networking or IAM. The schedule matters less than having an owner who reviews the result and decides whether to revert the change or codify it.
Does ignore_changes hide drift?
Yes, for the attributes you list. Terraform ignores those attributes when planning updates, so changes to them won't be proposed. Use it for fields another system legitimately owns, such as tags set by an agent, and keep the list short and commented.
→ Bring your Terraform repos and architecture together in IaC Orchestration
Stop finding drift during the incident
Drift is inevitable. Finding it during the next outage is optional. Put a refresh-only plan on a schedule, give every workspace an owner, and make every drift ticket end in revert, accept or import. Then keep the architecture view in sync, so the diagram your reviewers trust matches what's running.
Architecto connects your IaC, your live environments and your architecture diagrams, so drift turns into a reviewable finding with context instead of a surprise.