0
0
Terraformcloud~5 mins

Terraform plan for preview - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Terraform plan for preview
O(n)
Understanding Time Complexity

When using Terraform plan to preview changes, it is important to understand how the time to generate this preview grows as the number of resources increases.

We want to know how the number of resources affects the time Terraform takes to prepare the plan.

Scenario Under Consideration

Analyze the time complexity of running a Terraform plan on multiple resources.


resource "aws_instance" "example" {
  count         = var.instance_count
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

output "instance_ids" {
  value = aws_instance.example[*].id
}

This code creates multiple AWS instances based on a variable count and outputs their IDs. Terraform plan previews the changes before applying.

Identify Repeating Operations

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

  • Primary operation: Terraform queries the state and provider APIs for each resource to check current and desired states.
  • How many times: Once per resource instance, so it repeats as many times as the count of resources.
How Execution Grows With Input

As the number of resources increases, the number of API calls and checks grows proportionally.

Input Size (n)Approx. API Calls/Operations
10About 10 resource checks
100About 100 resource checks
1000About 1000 resource checks

Pattern observation: The work grows directly with the number of resources, so doubling resources roughly doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to prepare the plan grows linearly with the number of resources.

Common Mistake

[X] Wrong: "Terraform plan time stays the same no matter how many resources I have."

[OK] Correct: Each resource requires separate checks, so more resources mean more work and longer plan times.

Interview Connect

Understanding how Terraform plan scales helps you design infrastructure that is easier to manage and predict in real projects.

Self-Check

"What if we used modules that create multiple resources internally? How would that affect the time complexity of the plan?"