Drift Detection and Remediation
What you'll learn: How to automatically detect when your real infrastructure no longer matches your Terraform code and restore it to the desired state.
What Is Configuration Drift?
Configuration drift occurs when your actual cloud infrastructure changes outside of Terraform—someone modifies a security group in the AWS console, a script updates a database parameter, or an autoscaling event alters instance counts. Your Terraform state becomes outdated, and your infrastructure no longer matches your code.
Detecting Drift at Scale
For large infrastructures, manual drift detection is impractical. You need automated scanning that regularly runs terraform plan across all your workspaces and stacks. This produces a report showing which resources have drifted.
Think of it like a home security system: instead of checking every door and window manually each night, sensors continuously monitor and alert you to changes.
Detection Patterns
- Scheduled CI/CD jobs that run
terraform plan -detailed-exitcode(exits with code 2 if drift detected) - Terraform Cloud's drift detection feature for automatic monitoring
- Custom scripts that parse plan output and send alerts to Slack or PagerDuty
Remediation Strategies
Once drift is detected, you have options:
- Auto-remediate: Run
terraform applyautomatically to restore desired state (risky—use with caution) - Manual review: Alert teams to review and approve fixes
- Update code: If the drift was intentional, import the changes into your Terraform configuration
Large teams often use a semi-automated approach: detect drift automatically, alert on-call engineers, then require human approval before remediation.
Key Takeaway: Drift detection prevents infrastructure from silently diverging from your code by continuously scanning with terraform plan and triggering remediation workflows to restore consistency at scale.