Splat expressions in Terraform - Time & Space Complexity
We want to understand how using splat expressions affects the number of operations Terraform performs.
Specifically, how does the work grow when we use splat expressions on multiple resources?
Analyze the time complexity of the following operation sequence.
resource "aws_instance" "example" {
count = var.instance_count
ami = var.ami_id
instance_type = "t2.micro"
}
output "instance_ids" {
value = aws_instance.example[*].id
}
This code creates multiple instances and uses a splat expression to collect their IDs into a list.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Creating each aws_instance resource and retrieving its ID.
- How many times: Once per instance, equal to the count variable.
As the number of instances increases, the number of API calls and data retrievals grows proportionally.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 instance creations + 10 ID retrievals |
| 100 | 100 instance creations + 100 ID retrievals |
| 1000 | 1000 instance creations + 1000 ID retrievals |
Pattern observation: The operations grow linearly with the number of instances.
Time Complexity: O(n)
This means the work grows directly in proportion to the number of resources you manage with the splat expression.
[X] Wrong: "Using a splat expression makes Terraform do all operations only once regardless of resource count."
[OK] Correct: Each resource still requires its own creation and data retrieval; the splat just collects results but does not reduce the number of operations.
Understanding how resource counts affect operation numbers helps you design efficient infrastructure code and explain your reasoning clearly.
"What if we replaced the splat expression with individual references to each resource ID? How would the time complexity change?"