Interview Prep/Terraform/Lost, Corrupted and Drifted State

State is gone and the bucket had no versioning. How do you recover a production stack?

AdvancedTroubleshootingLost, Corrupted and Drifted State
Answer

Likely causes → Unversioned bucket, local state on a lost laptop, or a CI workspace that used local state.

Diagnose → Search for any copy first: terraform.tfstate.backup files, CI artifacts, old laptops, HCP state history. Inventory real resources by tag:

aws resourcegroupstaggingapi get-resources --tag-filters Key=stack,Values=prod-app \
  --query 'ResourceTagMappingList[].ResourceARN'

Fix → Rebuild state with import blocks (Terraform 1.5+), one per resource, in a fresh empty state:

import {
  to = aws_vpc.main
  id = "vpc-0a1b2c3d4e5f67890"
}

Iterate terraform plan until it shows 0 to add, 0 to change, 0 to destroy, fixing code where it differs.

Prevent → Versioned, KMS-encrypted remote state with restricted delete, plus consistent tagging (stack, env, managed-by=terraform) so an inventory is possible.

All Terraform questions Roadmap: Terraform in production

More on Lost, Corrupted and Drifted State