# Terraform workflow: rebuild state after state loss
## When
The state file was deleted, the backend bucket was lost, or corruption is unrecoverable. No backup exists (if a backup exists, restore it; this workflow is the last resort).
## Steps
1. Stop all applies and CI jobs touching this workspace. Recovery and concurrent writes do not mix.
2. Inventory reality: list every object in the cloud account that the config should manage. Tagging discipline pays off here; without it this is manual.
3. Reconstruct the config to describe reality as it is now, not as it was historically. Write it fresh; do not try to reproduce the old config from memory.
4. Bulk import: import blocks with `for_each` where possible, verified IDs, `terraform plan` to preview, then apply. Work resource type by resource type.
5. Converge: iterate config until `terraform plan` is clean. The clean plan is the proof the state matches reality.
6. Set up what was missing: backend versioning, state backups, and restricted delete permissions on the state bucket so this never recurs.
## Rules for agents
1. This is the incident where patience matters most. Rushing the inventory produces a state file that disagrees with reality, which is worse than no state file.
2. Objects you cannot identify: do not import blindly. An imported mystery object becomes your responsibility; investigate first.
3. Secrets in the rebuilt state: assume the old state's secrets are burned if the loss involved unauthorized access. Rotate after recovery.
4. Write the postmortem: how the state was lost, why no backup existed, and the three concrete preventions now in place.