Prevent_destroy lifecycle rule in Terraform - Time & Space 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?
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.
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
countvalue).
As the number of buckets increases, Terraform checks each one to prevent accidental deletion.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of resources.
Time Complexity: O(n)
This means the time to verify destruction prevention grows linearly with the number of resources.
[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.
Understanding how lifecycle rules affect operation counts shows you can predict infrastructure management costs and behavior.
What if we removed prevent_destroy from some resources? How would the time complexity change?