Dynamic blocks vs for_each decision in Terraform - Performance Comparison
We want to understand how the number of operations grows when using dynamic blocks versus for_each in Terraform.
Which approach causes more repeated work as we add more items?
Analyze the time complexity of these two Terraform snippets creating multiple sub-blocks.
resource "aws_security_group" "example" {
name = "example"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}
resource "aws_security_group" "example_for_each" {
name = "example-for-each"
ingress = [for rule in var.ingress_rules : {
from_port = rule.from_port
to_port = rule.to_port
protocol = rule.protocol
cidr_blocks = rule.cidr_blocks
}]
}
Both create multiple ingress rules, one using dynamic blocks, the other using for_each in a list.
Look at what repeats as the number of ingress rules grows.
- Primary operation: Creating one ingress rule block per item in the input list.
- How many times: Once for each ingress rule in
var.ingress_rules.
As you add more ingress rules, Terraform creates more blocks or list items.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 ingress blocks created |
| 100 | 100 ingress blocks created |
| 1000 | 1000 ingress blocks created |
Pattern observation: The number of operations grows directly with the number of ingress rules.
Time Complexity: O(n)
This means the work grows in a straight line as you add more ingress rules.
[X] Wrong: "Using dynamic blocks is slower because it loops inside Terraform, but for_each is faster."
[OK] Correct: Both approaches create one block per item, so the number of operations grows the same way. The difference is mostly in syntax, not performance.
Understanding how repeating resource blocks scale helps you design infrastructure code that stays manageable as it grows.
What if we nested dynamic blocks inside each other? How would the time complexity change?