Iterator variable in Terraform - Time & Space Complexity
When using an iterator variable in Terraform, we want to know how the number of operations changes as we loop over more items.
We ask: How does the work grow when the list we iterate over gets bigger?
Analyze the time complexity of this Terraform resource creation using an iterator variable.
resource "aws_instance" "example" {
for_each = { for name in var.instance_names : name => name }
ami = "ami-123456"
instance_type = "t2.micro"
tags = {
Name = each.key
}
}
This code creates one AWS instance for each name in the input list.
Look at what repeats as the input list grows.
- Primary operation: Creating an AWS instance resource for each item.
- How many times: Once per item in
var.instance_names.
As the list of instance names grows, the number of AWS instances created grows the same way.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 AWS instance creations |
| 100 | 100 AWS instance creations |
| 1000 | 1000 AWS instance creations |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means if you double the number of items, the work roughly doubles too.
[X] Wrong: "Using an iterator variable runs all resources at once, so time stays the same no matter how many items."
[OK] Correct: Each resource still needs to be created separately, so more items mean more work and more API calls.
Understanding how looping over resources affects deployment time helps you design efficient infrastructure and explain your choices clearly.
"What if we changed from a list to a map for the iterator variable? How would the time complexity change?"