0
0
Terraformcloud~5 mins

Dynamic blocks vs for_each decision in Terraform - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Dynamic blocks vs for_each decision
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As you add more ingress rules, Terraform creates more blocks or list items.

Input Size (n)Approx. Api Calls/Operations
1010 ingress blocks created
100100 ingress blocks created
10001000 ingress blocks created

Pattern observation: The number of operations grows directly with the number of ingress rules.

Final Time Complexity

Time Complexity: O(n)

This means the work grows in a straight line as you add more ingress rules.

Common Mistake

[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.

Interview Connect

Understanding how repeating resource blocks scale helps you design infrastructure code that stays manageable as it grows.

Self-Check

What if we nested dynamic blocks inside each other? How would the time complexity change?