Data source block syntax in Terraform - Time & Space 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.
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.
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.
As the number of matching AMIs grows, the API call returns more data to process.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 1 API call returning 10 items |
| 100 | 1 API call returning 100 items |
| 1000 | 1 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.
Time Complexity: O(n)
This means the time grows linearly with the number of matching resources returned by the data source.
[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.
Understanding how data source calls scale helps you design efficient Terraform configurations and explain your choices clearly.
"What if we added multiple data source blocks each fetching different AMIs? How would the time complexity change?"