0
0
Terraformcloud~5 mins

Data source block syntax in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Data source block syntax
O(n)
Understanding Time Complexity

When Terraform runs, it often reads existing cloud resources using data sources.

We want to know how the time to read these resources changes as we ask for more data.

Scenario Under Consideration

Analyze the time complexity of this data source usage.

data "aws_ami" "example" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

This block fetches the latest Amazon Linux 2 AMI matching a name pattern.

Identify Repeating Operations

Look at what happens when Terraform runs this data source.

  • Primary operation: API call to AWS to list AMIs matching filters.
  • How many times: Once per data source block during plan or apply.
How Execution Grows With Input

As the number of matching AMIs grows, the API call returns more data to process.

Input Size (n)Approx. API Calls/Operations
101 API call returning 10 items
1001 API call returning 100 items
10001 API call returning 1000 items

Pattern observation: The number of API calls stays the same, but processing time grows with the number of items returned.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of matching resources returned by the data source.

Common Mistake

[X] Wrong: "The data source always takes the same time no matter how many resources match."

[OK] Correct: Even though the API call count is one, processing more returned items takes more time.

Interview Connect

Understanding how data source calls scale helps you design efficient Terraform configurations and explain your choices clearly.

Self-Check

"What if we added multiple data source blocks each fetching different AMIs? How would the time complexity change?"