What is prevent_destroy in Terraform and How It Works
prevent_destroy is a lifecycle setting that stops a resource from being deleted accidentally. When set to true, Terraform will block any plan or apply that tries to destroy the resource, helping protect important infrastructure.How It Works
Think of prevent_destroy as a safety lock on a valuable item. When you enable it on a Terraform resource, you tell Terraform, "Don't delete this resource no matter what." If you try to remove or replace the resource, Terraform will stop and show an error instead of deleting it.
This works because Terraform checks the lifecycle rules before making changes. If prevent_destroy is set to true, any action that would destroy the resource is blocked. This helps avoid accidental loss of critical infrastructure, like databases or servers.
Example
This example shows how to use prevent_destroy to protect an AWS S3 bucket from deletion.
resource "aws_s3_bucket" "example" { bucket = "my-important-bucket" lifecycle { prevent_destroy = true } }
When to Use
Use prevent_destroy when you have resources that must not be deleted accidentally. For example:
- Databases holding important data
- Production servers or load balancers
- Critical storage buckets or networking components
This setting is especially useful in teams or automated pipelines where mistakes can happen. It acts as a guardrail to keep essential infrastructure safe.
Key Points
- prevents accidental deletion: Blocks destroy actions on resources.
- set in lifecycle block: Added inside the resource's lifecycle configuration.
- causes errors on destroy: Terraform shows an error if destroy is attempted.
- helps protect critical resources: Useful for databases, servers, and storage.
Key Takeaways
prevent_destroy stops Terraform from deleting a resource accidentally.prevent_destroy = true.