Terraform apply for execution - Time & Space Complexity
When we run terraform apply, it creates or updates cloud resources. We want to understand how the time it takes grows as we add more resources.
How does the number of resources affect the total work Terraform does?
Analyze the time complexity of applying a Terraform configuration that creates multiple resources.
resource "aws_instance" "example" {
count = var.instance_count
ami = "ami-12345678"
instance_type = "t2.micro"
}
output "instance_ids" {
value = aws_instance.example[*].id
}
This code creates a number of virtual machines equal to instance_count. Terraform provisions each instance one by one.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Creating each virtual machine resource via cloud API calls.
- How many times: Once per instance, equal to
instance_count.
As you increase the number of instances, Terraform makes more API calls, one per instance.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 API calls to create 10 instances |
| 100 | 100 API calls to create 100 instances |
| 1000 | 1000 API calls to create 1000 instances |
Pattern observation: The number of API calls grows directly with the number of instances.
Time Complexity: O(n)
This means the time to apply grows in a straight line with the number of resources you create.
[X] Wrong: "Terraform applies all resources instantly, so time stays the same no matter how many resources."
[OK] Correct: Each resource requires a separate API call and provisioning time, so more resources mean more total time.
Understanding how Terraform scales with resource count helps you design efficient infrastructure and estimate deployment times in real projects.
What if Terraform could create multiple resources in parallel? How would the time complexity change?