0
0
Terraformcloud~5 mins

Iterator variable in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iterator variable
O(n)
Understanding Time Complexity

When using an iterator variable in Terraform, we want to know how the number of operations changes as we loop over more items.

We ask: How does the work grow when the list we iterate over gets bigger?

Scenario Under Consideration

Analyze the time complexity of this Terraform resource creation using an iterator variable.


resource "aws_instance" "example" {
  for_each = { for name in var.instance_names : name => name }

  ami           = "ami-123456"
  instance_type = "t2.micro"
  tags = {
    Name = each.key
  }
}
    

This code creates one AWS instance for each name in the input list.

Identify Repeating Operations

Look at what repeats as the input list grows.

  • Primary operation: Creating an AWS instance resource for each item.
  • How many times: Once per item in var.instance_names.
How Execution Grows With Input

As the list of instance names grows, the number of AWS instances created grows the same way.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of items, the work roughly doubles too.

Common Mistake

[X] Wrong: "Using an iterator variable runs all resources at once, so time stays the same no matter how many items."

[OK] Correct: Each resource still needs to be created separately, so more items mean more work and more API calls.

Interview Connect

Understanding how looping over resources affects deployment time helps you design efficient infrastructure and explain your choices clearly.

Self-Check

"What if we changed from a list to a map for the iterator variable? How would the time complexity change?"