Prompt
How do I detect drift in Terraform-managed infrastructure?
Latest observation
Terraform drift means the real-world infrastructure has changed outside of Terraform, so your state no longer matches what’s actually deployed.
Common ways to detect drift
1. Run terraform plan regularly
The standard way to detect drift is:
terraform plan
If anything has changed outside Terraform, the plan will show updates, recreations, or deletions needed to bring the real environment back in sync.
To compare against state only, without proposing changes, you can also use:
terraform plan -refresh-only
This refreshes state from the provider and shows what has drifted.
2. Use terraform refresh behavior via plan/apply
Terraform now handles refresh during plan/apply. A plan will typically detect external changes by querying the provider and comparing them to state.
3. Automate drift detection in CI/CD
Run scheduled jobs that execute:
terraform init -input=false
terraform plan -refresh-only -detailed-exitcode
Then check the exit code:
0= no drift2= drift detected1= error
This is a common pattern for alerting.
4. Use Terraform Cloud / Terraform Enterprise
If you use Terraform Cloud or Enterprise, you can enable drift detection and run speculative plans on a schedule to find changes outside Terraform.
5. Watch for provider-side changes
Some cloud providers expose their own audit/change logs:
- AWS CloudTrail
- Azure Activity Log
- GCP Audit Logs
These don’t replace Terraform drift detection, but they help explain what changed and who changed it.
Best practices
- Prefer making all changes through Terraform, not manually in the console.
- Schedule periodic
plan -refresh-onlyruns. - Alert on drift in CI or Terraform Cloud.
- Protect critical resources with IAM permissions and policy controls.
- Keep state secure and up to date.
Example drift check script
#!/usr/bin/env bash
set -e
terraform init -input=false
terraform plan -refresh-only -detailed-exitcode
case $? in
0) echo "No drift detected" ;;
2) echo "Drift detected" ;;
*) echo "Terraform error" ; exit 1 ;;
esac
If you want, I can also show:
- a GitHub Actions drift check workflow
- a Terraform Cloud drift detection setup
- how to detect drift for a specific provider like AWS/Azure/GCP