Arguments and expressions in Terraform - Time & Space Complexity
We want to understand how the time to process arguments and expressions in Terraform changes as we add more inputs.
Specifically, how does the number of expressions affect the work Terraform does?
Analyze the time complexity of the following Terraform code snippet.
variable "names" {
type = list(string)
}
resource "aws_instance" "example" {
count = length(var.names)
name = var.names[count.index]
tags = { Name = var.names[count.index] }
}
This code creates one instance per name in the list, using expressions to assign names and tags.
Look at what repeats as the input list grows.
- Primary operation: Creating one resource per item in the input list.
- How many times: Once for each name in the list (n times).
As the list of names grows, Terraform creates more resources and evaluates more expressions.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 resource creations and expression evaluations |
| 100 | 100 resource creations and expression evaluations |
| 1000 | 1000 resource creations and expression evaluations |
Pattern observation: The work grows directly with the number of input items.
Time Complexity: O(n)
This means the time to process arguments and expressions grows linearly with the number of input items.
[X] Wrong: "Adding more items won't affect processing time much because expressions are simple."
[OK] Correct: Each item causes Terraform to evaluate expressions and create resources, so more items mean more work.
Understanding how input size affects resource creation helps you design efficient infrastructure and explain your reasoning clearly.
"What if we used a fixed number of resources but changed the complexity of expressions inside each resource? How would the time complexity change?"