Dynamic block syntax in Terraform - Time & Space Complexity
We want to understand how the time to apply Terraform changes grows when using dynamic blocks.
Specifically, how does adding more repeated blocks affect the number of operations Terraform performs?
Analyze the time complexity of this Terraform dynamic block example.
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 a security group with multiple ingress rules generated dynamically from a list.
Look at what repeats when Terraform applies this configuration.
- Primary operation: Creating or updating each ingress rule block inside the security group.
- How many times: Once for each item in
var.ingress_rules.
As the number of ingress rules increases, Terraform performs more operations.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | About 10 ingress rule operations |
| 100 | About 100 ingress rule operations |
| 1000 | About 1000 ingress rule operations |
Pattern observation: The number of operations grows directly with the number of ingress rules.
Time Complexity: O(n)
This means the time to apply changes grows linearly with the number of dynamic blocks.
[X] Wrong: "Adding more dynamic blocks won't affect apply time much because Terraform handles them all at once."
[OK] Correct: Each dynamic block creates separate resources or settings, so Terraform must process each one individually, increasing apply time.
Understanding how repeated resource blocks affect deployment time helps you design efficient infrastructure code and explain your choices clearly.
What if we replaced the dynamic block with a fixed number of static blocks? How would the time complexity change?