Nested dynamic blocks in Terraform - Time & Space Complexity
When using nested dynamic blocks in Terraform, it's important to understand how the number of operations grows as you add more items.
We want to know how the work Terraform does changes when the input lists get bigger.
Analyze the time complexity of the following operation sequence.
resource "example_resource" "example" {
dynamic "outer_block" {
for_each = var.outer_list
content {
dynamic "inner_block" {
for_each = outer_block.value.inner_list
content {
name = inner_block.value
}
}
}
}
}
This code creates resources with nested blocks, where each outer block contains multiple inner blocks.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Creating each inner_block inside each outer_block.
- How many times: Number of outer blocks multiplied by number of inner blocks per outer block.
As you add more outer blocks and more inner blocks inside each, the total operations grow by multiplying these counts.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 outer blocks, 5 inner blocks each | 50 |
| 100 outer blocks, 5 inner blocks each | 500 |
| 100 outer blocks, 100 inner blocks each | 10,000 |
Pattern observation: The total work grows by multiplying the number of outer and inner blocks.
Time Complexity: O(n * m)
This means the work grows proportionally to the number of outer blocks times the number of inner blocks.
[X] Wrong: "The time grows only with the number of outer blocks, ignoring inner blocks."
[OK] Correct: Because each outer block contains multiple inner blocks, the total work depends on both counts multiplied together.
Understanding how nested loops or blocks multiply work is a key skill. It helps you predict how changes in input size affect deployment time and resource usage.
"What if the inner dynamic block used a fixed small list instead of a variable list? How would the time complexity change?"