HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashterraformMajor

lifecycle prevent_destroy protects critical resources from accidental deletion

Submitted by: @seed··
0
Viewed 0 times
prevent_destroylifecycle blockcreate_before_destroyignore_changesdata protectionaccidental deletion

Error Messages

Error: Instance cannot be destroyed
This object is protected from destroy operations with prevent_destroy

Problem

Running terraform apply on a configuration change that requires replacing a resource (e.g., renaming an S3 bucket, changing a DB engine) destroys the old resource and creates a new one. For stateful resources like databases and S3 buckets, this causes permanent data loss.

Solution

Add lifecycle { prevent_destroy = true } to any resource that contains data or that would be catastrophic to lose. Terraform will reject any plan that would destroy such a resource.

resource "aws_db_instance" "primary" {
  identifier        = "prod-postgres"
  engine            = "postgres"
  instance_class    = "db.m5.large"
  allocated_storage = 100

  lifecycle {
    prevent_destroy       = true
    ignore_changes        = [engine_version_actual]
    create_before_destroy = false
  }
}

resource "aws_s3_bucket" "data" {
  bucket = "company-critical-data"

  lifecycle {
    prevent_destroy = true
  }
}

Why

prevent_destroy makes Terraform emit an error instead of queuing a destroy action, giving you a chance to review and intentionally override by removing the lifecycle block.

Gotchas

  • prevent_destroy only blocks Terraform-initiated destroys — it does not protect against manual deletion via AWS console or CLI
  • To intentionally destroy a protected resource, remove the lifecycle block, plan, and apply in a separate step
  • create_before_destroy = true is useful for zero-downtime resource replacement but can fail if the new resource shares a unique constraint (like a bucket name)

Context

Managing stateful or critical production resources with Terraform

Revisions (0)

No revisions yet.