0
0
Terraformcloud~5 mins

Nested dynamic blocks in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested dynamic blocks
O(n * m)
Understanding Time Complexity

When using nested dynamic blocks in Terraform, it's important to understand how the number of operations grows as you add more items.

We want to know how the work Terraform does changes when the input lists get bigger.

Scenario Under Consideration

Analyze the time complexity of the following operation sequence.

resource "example_resource" "example" {
  dynamic "outer_block" {
    for_each = var.outer_list
    content {
      dynamic "inner_block" {
        for_each = outer_block.value.inner_list
        content {
          name = inner_block.value
        }
      }
    }
  }
}

This code creates resources with nested blocks, where each outer block contains multiple inner blocks.

Identify Repeating Operations

Identify the API calls, resource provisioning, data transfers that repeat.

  • Primary operation: Creating each inner_block inside each outer_block.
  • How many times: Number of outer blocks multiplied by number of inner blocks per outer block.
How Execution Grows With Input

As you add more outer blocks and more inner blocks inside each, the total operations grow by multiplying these counts.

Input Size (n)Approx. API Calls/Operations
10 outer blocks, 5 inner blocks each50
100 outer blocks, 5 inner blocks each500
100 outer blocks, 100 inner blocks each10,000

Pattern observation: The total work grows by multiplying the number of outer and inner blocks.

Final Time Complexity

Time Complexity: O(n * m)

This means the work grows proportionally to the number of outer blocks times the number of inner blocks.

Common Mistake

[X] Wrong: "The time grows only with the number of outer blocks, ignoring inner blocks."

[OK] Correct: Because each outer block contains multiple inner blocks, the total work depends on both counts multiplied together.

Interview Connect

Understanding how nested loops or blocks multiply work is a key skill. It helps you predict how changes in input size affect deployment time and resource usage.

Self-Check

"What if the inner dynamic block used a fixed small list instead of a variable list? How would the time complexity change?"