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. 1.Refresh state to match actual infrastructure:
  2. 2.```bash
  3. 3.terraform refresh
  4. 4.`
  5. 5.Note: This updates state but does NOT change infrastructure.
  6. 6.Import manually-created resources:
  7. 7.```bash
  8. 8.terraform import aws_s3_bucket.manual-bucket my-manual-bucket
  9. 9.# Then add the resource block to your config
  10. 10.`
  11. 11.Ignore changes that should be managed externally:
  12. 12.```hcl
  13. 13.resource "aws_s3_bucket" "example" {
  14. 14.bucket = "my-bucket"
  15. 15.lifecycle {
  16. 16.ignore_changes = [tags, logging]
  17. 17.}
  18. 18.}
  19. 19.`

Prevention - Restrict console access for production resources - Use Terraform Cloud drift detection - Implement SCPs to prevent manual changes - Run `terraform plan` on a schedule to detect drift early - Use AWS Config or Azure Policy for compliance monitoring