Why dynamic blocks reduce repetition in Terraform - Performance Analysis
We want to see how using dynamic blocks in Terraform affects the number of operations as we add more repeated configurations.
How does the work grow when we avoid writing repeated blocks manually?
Analyze the time complexity of this Terraform snippet using a dynamic block.
resource "aws_security_group" "example" {
name = "example-sg"
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
}
}
}
This creates multiple ingress rules inside one security group using a dynamic block looping over input rules.
Look at what repeats when Terraform applies this configuration.
- Primary operation: Creating each ingress rule inside the security group.
- How many times: Once per item in
var.ingress_rules.
As you add more ingress rules, Terraform creates more ingress blocks dynamically.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 ingress rule creations |
| 100 | 100 ingress rule creations |
| 1000 | 1000 ingress rule creations |
Pattern observation: The number of operations grows directly with the number of rules.
Time Complexity: O(n)
This means the work grows in a straight line with the number of repeated blocks you define.
[X] Wrong: "Using dynamic blocks makes Terraform do fewer operations overall."
[OK] Correct: Dynamic blocks just help write less code, but Terraform still creates each resource or sub-block once per item.
Understanding how repeating configurations scale helps you design efficient infrastructure code and explain your choices clearly.
"What if we replaced the dynamic block with multiple static blocks written manually? How would the time complexity change?"