0
0
Terraformcloud~5 mins

Prevent_destroy lifecycle rule in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Prevent_destroy lifecycle rule
O(n)
Understanding Time Complexity

We want to understand how the use of the prevent_destroy lifecycle rule affects the number of operations Terraform performs.

Specifically, we ask: How does this rule impact the steps Terraform takes when destroying resources?

Scenario Under Consideration

Analyze the time complexity of applying prevent_destroy in a resource lifecycle.

resource "aws_s3_bucket" "example" {
  count = var.bucket_count

  bucket = "example-bucket-${count.index}"

  lifecycle {
    prevent_destroy = true
  }
}

This code creates multiple S3 buckets and prevents them from being destroyed by Terraform.

Identify Repeating Operations

Look at what Terraform does repeatedly when this rule is set.

  • Primary operation: Checking each resource for destruction permission before destroy.
  • How many times: Once per resource instance (equal to count value).
How Execution Grows With Input

As the number of buckets increases, Terraform checks each one to prevent accidental deletion.

Input Size (n)Approx. API Calls/Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of checks grows directly with the number of resources.

Final Time Complexity

Time Complexity: O(n)

This means the time to verify destruction prevention grows linearly with the number of resources.

Common Mistake

[X] Wrong: "Using prevent_destroy stops Terraform from checking resources during destroy."

[OK] Correct: Terraform still checks every resource to enforce the rule, so the operation count grows with resource count.

Interview Connect

Understanding how lifecycle rules affect operation counts shows you can predict infrastructure management costs and behavior.

Self-Check

What if we removed prevent_destroy from some resources? How would the time complexity change?