Introduction When infrastructure is modified outside Terraform (console changes, CLI commands, emergency fixes), the next terraform plan shows a diff between the desired state and actual state. This "drift" can cause Terraform to undo manual changes or fail unexpectedly.
Symptoms - `terraform plan` shows unexpected changes you did not make in code - Resources marked for replacement due to external modifications - Security group rules appearing/disappearing that you did not change - Tags or metadata modified by external automation - Plan shows ~update or -/+replace for resources you did not touch
Common Causes - Manual changes via cloud console or CLI - Other IaC tools (CloudFormation, CDK) managing same resources - Automated security tools modifying security groups - Cloud provider auto-updating resources (e.g., RDS minor version) - Tags added by cloud provider (e.g., AWS cost allocation tags)
Step-by-Step Fix 1. **Review the drift in detail**: ```bash terraform plan -detailed terraform plan -out=drift.plan terraform show drift.plan ```
- 1.Refresh state to match actual infrastructure:
- 2.```bash
- 3.terraform refresh
- 4.
` - 5.Note: This updates state but does NOT change infrastructure.
- 6.Import manually-created resources:
- 7.```bash
- 8.terraform import aws_s3_bucket.manual-bucket my-manual-bucket
- 9.# Then add the resource block to your config
- 10.
` - 11.Ignore changes that should be managed externally:
- 12.```hcl
- 13.resource "aws_s3_bucket" "example" {
- 14.bucket = "my-bucket"
- 15.lifecycle {
- 16.ignore_changes = [tags, logging]
- 17.}
- 18.}
- 19.
`