Querying existing resources in Terraform - Time & Space Complexity
When Terraform queries existing resources, it asks the cloud provider for information. Understanding how long this takes helps us plan and predict deployment times.
We want to know how the number of queries grows as we ask about more resources.
Analyze the time complexity of the following operation sequence.
data "aws_instance" "example" {
count = var.instance_count
instance_id = var.instance_ids[count.index]
}
output "instance_ips" {
value = [for i in data.aws_instance.example : i.public_ip]
}
This code queries details for multiple existing AWS instances by their IDs and outputs their public IPs.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Querying each AWS instance's details via the AWS API.
- How many times: Once per instance ID in the list (var.instance_count times).
Each additional instance ID adds one more query to the cloud provider.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 queries |
| 100 | 100 queries |
| 1000 | 1000 queries |
Pattern observation: The number of queries grows directly with the number of instances queried.
Time Complexity: O(n)
This means the time to query grows in a straight line as you ask about more resources.
[X] Wrong: "Querying multiple resources happens all at once, so time stays the same no matter how many."
[OK] Correct: Each resource query is a separate call, so more resources mean more calls and more time.
Knowing how querying existing resources scales helps you design efficient infrastructure code and shows you understand cloud interactions clearly.
"What if we batch queried multiple resources in one call? How would the time complexity change?"