Interview Prep/Terraform/Lost, Corrupted and Drifted State

Someone deleted the state object from the S3 bucket. `terraform plan` now wants to create 140 resources that already exist.

IntermediateTroubleshootingLost, Corrupted and Drifted State
Answer

Likely causes → The object was deleted (by hand, by a lifecycle rule or by a cleanup script). With versioning on, S3 only added a delete marker.

Diagnose →

aws s3api list-object-versions --bucket acme-tfstate --prefix prod/app/terraform.tfstate \
  --query '{versions:Versions[].[VersionId,LastModified,Size],markers:DeleteMarkers[].[VersionId,LastModified]}'

Fix → Do not apply. Remove the delete marker (restores the latest version) or copy a known-good version back:

aws s3api delete-object --bucket acme-tfstate --key prod/app/terraform.tfstate --version-id <delete-marker-id>
terraform plan   # should show no or small changes

Prevent → Versioning + MFA delete or a bucket policy denying s3:DeleteObject on *.tfstate for humans, and a noncurrent-version retention lifecycle rule (for example 90 days).

All Terraform questions Roadmap: Terraform in production

More on Lost, Corrupted and Drifted State