Resource arguments and attributes in Terraform - Time & Space Complexity
When using Terraform, we want to know how the time to apply changes grows as we add more resources or use more arguments.
We ask: How does the number of resource arguments and attributes affect the work Terraform does?
Analyze the time complexity of creating multiple resources with arguments and reading their attributes.
resource "aws_instance" "example" {
count = var.instance_count
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = "ExampleInstance-${count.index}"
}
}
output "instance_ids" {
value = aws_instance.example[*].id
}
This code creates multiple instances based on a count variable and outputs their IDs.
Look at what repeats as the input grows.
- Primary operation: Creating each aws_instance resource and reading its attributes.
- How many times: Once per instance, equal to
var.instance_count.
As you increase the number of instances, Terraform creates and reads attributes for each one.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 resource creations + 10 attribute reads |
| 100 | 100 resource creations + 100 attribute reads |
| 1000 | 1000 resource creations + 1000 attribute reads |
Pattern observation: The work grows directly with the number of instances.
Time Complexity: O(n)
This means the time to apply grows linearly with the number of resources created and their attributes read.
[X] Wrong: "Adding more arguments or attributes does not affect execution time much."
[OK] Correct: Each argument and attribute can cause extra API calls or processing, so more arguments mean more work per resource.
Understanding how resource count and arguments affect execution helps you design efficient infrastructure code and explain your choices clearly.
"What if we replaced count with for_each using a map? How would the time complexity change?"