Dynamic blocks in security groups in Terraform - Time & Space Complexity
We want to understand how the time to create security group rules changes when using dynamic blocks in Terraform.
Specifically, how does adding more rules affect the number of operations Terraform performs?
Analyze the time complexity of this Terraform snippet using dynamic blocks to create security group rules.
resource "aws_security_group" "example" {
name = "example-sg"
description = "Example security group"
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 code creates a security group with multiple ingress rules defined dynamically from a list variable.
- Primary operation: Creating or updating each ingress rule in the security group.
- How many times: Once for each item in
var.ingress_rules.
As you add more ingress rules, Terraform makes more API calls to create or update those rules.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | About 10 calls for ingress rules |
| 100 | About 100 calls for ingress rules |
| 1000 | About 1000 calls for ingress rules |
Pattern observation: The number of operations grows directly with the number of rules.
Time Complexity: O(n)
This means the time to apply the security group grows linearly as you add more rules.
[X] Wrong: "Adding more rules won't affect apply time much because Terraform handles them all at once."
[OK] Correct: Each rule requires a separate API call to create or update, so more rules mean more calls and longer apply time.
Understanding how resource counts affect deployment time helps you design efficient infrastructure and explain your choices clearly.
What if we replaced the dynamic block with a single rule that allows all traffic? How would the time complexity change?