0
0
TerraformConceptBeginner · 3 min read

What is prevent_destroy in Terraform and How It Works

In Terraform, 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.

terraform
resource "aws_s3_bucket" "example" {
  bucket = "my-important-bucket"

  lifecycle {
    prevent_destroy = true
  }
}
Output
Terraform will block any attempt to delete the "my-important-bucket" S3 bucket and show an error during plan or apply.
🎯

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.
It is set inside the resource's lifecycle block as prevent_destroy = true.
Terraform will show an error if you try to destroy a protected resource.
Use it to protect important infrastructure like databases and production servers.
It acts as a safety lock to avoid costly mistakes in infrastructure management.