0
0
Terraformcloud~5 mins

For_each for map-based instances in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For_each for map-based instances
O(n)
Understanding Time Complexity

When using for_each with maps in Terraform, it's important to understand how the number of resources affects the work Terraform does.

We want to know how the number of API calls grows as we add more map entries.

Scenario Under Consideration

Analyze the time complexity of the following operation sequence.

resource "aws_instance" "example" {
  for_each = var.instances_map

  ami           = each.value.ami
  instance_type = each.value.instance_type
  tags = {
    Name = each.key
  }
}

This creates one AWS instance for each entry in a map variable, using the map's keys and values.

Identify Repeating Operations

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

  • Primary operation: Creating or updating one AWS instance per map entry.
  • How many times: Once for each key-value pair in the map.
How Execution Grows With Input

Each new map entry adds one more instance resource to create or update.

Input Size (n)Approx. API Calls/Operations
1010 instance creations or updates
100100 instance creations or updates
10001000 instance creations or updates

Pattern observation: The number of API calls grows directly with the number of map entries.

Final Time Complexity

Time Complexity: O(n)

This means the work grows linearly as you add more map entries.

Common Mistake

[X] Wrong: "Adding more map entries won't increase the number of API calls much because Terraform handles them all at once."

[OK] Correct: Each map entry creates a separate resource, so each requires its own API call, making the total grow with the number of entries.

Interview Connect

Understanding how resource counts affect API calls helps you design efficient infrastructure and explain your choices clearly in discussions.

Self-Check

"What if we changed the map to a list and used count instead of for_each? How would the time complexity change?"