0
0
Terraformcloud~5 mins

Create_before_destroy lifecycle rule in Terraform - Time & Space Complexity

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

We want to understand how the time to apply changes grows when using the create_before_destroy lifecycle rule in Terraform.

Specifically, how does this rule affect the number of resource operations as we increase resources?

Scenario Under Consideration

Analyze the time complexity of this Terraform resource with create_before_destroy lifecycle.

resource "aws_instance" "example" {
  count = var.instance_count

  ami           = "ami-123456"
  instance_type = "t2.micro"

  lifecycle {
    create_before_destroy = true
  }
}

This creates multiple AWS instances, ensuring new ones are created before old ones are destroyed.

Identify Repeating Operations

Look at what repeats when Terraform applies this configuration.

  • Primary operation: Creating and destroying each AWS instance resource.
  • How many times: Once per instance, twice per instance when replacing (create then destroy).
How Execution Grows With Input

As the number of instances increases, the operations grow accordingly.

Input Size (n)Approx. API Calls/Operations
10About 20 (create 10 new, destroy 10 old)
100About 200 (create 100 new, destroy 100 old)
1000About 2000 (create 1000 new, destroy 1000 old)

Pattern observation: Operations roughly double because each resource is created before the old one is destroyed.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of resources, doubling the operations compared to simple create or destroy.

Common Mistake

[X] Wrong: "Using create_before_destroy means Terraform will do twice as many operations regardless of resource count."

[OK] Correct: The doubling happens only when resources are replaced; if no replacement is needed, operations stay the same.

Interview Connect

Understanding how lifecycle rules affect operation counts helps you design infrastructure changes that minimize downtime and manage costs effectively.

Self-Check

"What if we removed create_before_destroy and used the default lifecycle? How would the time complexity change when replacing resources?"