0
0
Terraformcloud~5 mins

AMI lookup data source example in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: AMI lookup data source example
O(n)
Understanding Time Complexity

We want to understand how the time to find an AMI image changes as we look up more images.

Specifically, how does the number of API calls grow when searching for AMIs?

Scenario Under Consideration

Analyze the time complexity of the following operation sequence.

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

This code looks up the most recent Amazon Linux 2 AMI by filtering images owned by Amazon.

Identify Repeating Operations

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

  • Primary operation: AWS API call to search AMIs with filters
  • How many times: Once per data source usage in Terraform plan/apply
How Execution Grows With Input

The API call searches through available AMIs matching the filter. As the number of AMIs grows, the search internally checks more images.

Input Size (n)Approx. API Calls/Operations
101 API call, internal search over 10 images
1001 API call, internal search over 100 images
10001 API call, internal search over 1000 images

Pattern observation: The number of API calls stays the same, but the internal search work grows with the number of images.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the AMI grows linearly with the number of images available.

Common Mistake

[X] Wrong: "The lookup always takes the same time no matter how many AMIs exist."

[OK] Correct: The API call is one, but the search inside AWS checks all matching images, so more images mean more work.

Interview Connect

Understanding how cloud API calls scale helps you design efficient infrastructure code and anticipate delays.

Self-Check

"What if we removed the filter and searched all AMIs? How would the time complexity change?"