Terraform's destroy command is a powerful tool for removing infrastructure, but it must be used with caution. This article provides best practices for safely tearing down AWS resources managed by Terraform.
Understand the risk
terraform destroy deletes all resources defined in your configuration files. Without proper safeguards, you can accidentally remove production environments or stateful data.
Essential safeguards
- Use Terraform workspaces to isolate environments (dev, staging, prod).
- Enable
prevent_destroyon critical resources like databases. - Run
terraform plan -destroyto preview changes before executing. - Utilize state locking to prevent concurrent operations.
Step-by-step safe destroy
- Back up state: Copy your state file (
terraform.tfstate) to a secure location. - Review configuration: Ensure you're in the correct directory and workspace.
- Plan the destroy: Execute
terraform plan -destroy -out=destroy.tfplanto see what will be removed. - Approve: Run
terraform apply destroy.tfplanonly after confirming the plan matches your intent. - Verify: Check the AWS console or use CLI to ensure resources are gone.
What if something goes wrong?
If you accidentally destroy critical resources, restore from the backed-up state file and run terraform apply to recreate infrastructure.
Conclusion
By following these steps—plan, isolate, back up, and verify—you can confidently use terraform destroy without fear of accidental data loss.