Prompt
How do I detect drift between Terraform state and actual cloud resources?
Latest observation
To detect drift between Terraform state and real cloud resources, the usual approach is to compare the state Terraform knows about with the live infrastructure. Here are the practical options, from simplest to most robust:
1) Run terraform plan
This is the standard drift check.
terraform plan
If Terraform detects differences between the saved state and real resources, the plan will show changes.
For remote state / CI use
terraform plan -detailed-exitcode
Exit codes:
0= no changes2= changes/drift detected1= error
This is very useful in automation.
2) Refresh state before planning
Terraform typically refreshes state during plan, but you can explicitly use:
terraform apply -refresh-only
or in newer workflows:
terraform plan -refresh-only
This checks live resources against state and shows drift without proposing configuration changes.
Good use case
If someone changed resources manually in the cloud, refresh-only will update state to reflect actual resource values.
3) Use terraform refresh?
Historically, Terraform had:
terraform refresh
But this is generally deprecated in favor of plan -refresh-only or apply -refresh-only.
4) Automate drift detection in CI/CD
A common pattern is:
- run
terraform init - run
terraform plan -detailed-exitcode - alert on exit code
2
Example:
terraform init
terraform plan -detailed-exitcode -out=tfplan
Then parse the exit code in your CI system.
5) Use cloud/provider tools for independent checks
Terraform detects drift from its perspective, but you may also want external visibility:
- AWS: Config, CloudTrail, Resource Explorer
- Azure: Azure Policy, Resource Graph, Activity Log
- GCP: Cloud Asset Inventory, Audit Logs
These tools can help identify changes made outside Terraform, which you can then verify with terraform plan.
6) Compare state manually if needed
For troubleshooting:
terraform state list
terraform state show <resource_address>
Then compare to the actual cloud resource configuration.
This is more manual, but useful when diagnosing a specific resource.
Recommended workflow
For most teams:
- Store state remotely
- Run scheduled or CI-based drift checks:
terraform plan -detailed-exitcode - Investigate any non-zero drift
- Decide whether to:
- revert the manual change, or
- update Terraform configuration and re-apply, or
- intentionally accept drift and refresh state if appropriate
Important note
Terraform detects drift only for resources it manages in state. If a resource exists in the cloud but isn’t in state, Terraform won’t consider it drift—it’s just unmanaged.
If you want, I can also show you:
- a CI example for drift detection
- a script to alert on drift
- how drift detection differs for AWS/Azure/GCP