For_each for map-based instances in Terraform - Time & Space Complexity
When using for_each with maps in Terraform, it's important to understand how the number of resources affects the work Terraform does.
We want to know how the number of API calls grows as we add more map entries.
Analyze the time complexity of the following operation sequence.
resource "aws_instance" "example" {
for_each = var.instances_map
ami = each.value.ami
instance_type = each.value.instance_type
tags = {
Name = each.key
}
}
This creates one AWS instance for each entry in a map variable, using the map's keys and values.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Creating or updating one AWS instance per map entry.
- How many times: Once for each key-value pair in the map.
Each new map entry adds one more instance resource to create or update.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 instance creations or updates |
| 100 | 100 instance creations or updates |
| 1000 | 1000 instance creations or updates |
Pattern observation: The number of API calls grows directly with the number of map entries.
Time Complexity: O(n)
This means the work grows linearly as you add more map entries.
[X] Wrong: "Adding more map entries won't increase the number of API calls much because Terraform handles them all at once."
[OK] Correct: Each map entry creates a separate resource, so each requires its own API call, making the total grow with the number of entries.
Understanding how resource counts affect API calls helps you design efficient infrastructure and explain your choices clearly in discussions.
"What if we changed the map to a list and used count instead of for_each? How would the time complexity change?"