Terraform destroy for cleanup - Time & Space Complexity
When we run terraform destroy, it removes resources created by terraform. We want to understand how the time to clean up grows as we have more resources.
The question is: How does the number of resources affect the cleanup time?
Analyze the time complexity of the following operation sequence.
resource "aws_instance" "example" {
count = var.instance_count
ami = "ami-123456"
instance_type = "t2.micro"
}
// terraform destroy will remove all instances created
This code creates multiple instances based on a count variable. Destroy will remove all these instances.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: API call to delete each instance resource.
- How many times: Once per instance, so equal to the number of instances.
As the number of instances increases, the number of delete calls grows at the same rate.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 delete calls |
| 100 | 100 delete calls |
| 1000 | 1000 delete calls |
Pattern observation: The cleanup work grows directly with the number of resources.
Time Complexity: O(n)
This means the time to destroy grows linearly with the number of resources to remove.
[X] Wrong: "Destroying many resources takes the same time as destroying one."
[OK] Correct: Each resource requires a separate delete call, so more resources mean more work and more time.
Understanding how resource cleanup scales helps you plan infrastructure changes and estimate deployment times. This skill shows you think about real-world impacts of your code.
"What if terraform destroy could delete multiple resources in one API call? How would the time complexity change?"