Module outputs in Terraform - Time & Space Complexity
When using Terraform modules, outputs let us share information from one module to another.
We want to understand how the time to get these outputs changes as we add more outputs.
Analyze the time complexity of retrieving outputs from a module.
module "example" {
source = "./modules/example"
count = var.instance_count
}
output "instance_ids" {
value = [for m in module.example : m.instance_id]
}
This code calls a module multiple times and collects all instance IDs as output.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Retrieving each module instance's output value.
- How many times: Once per module instance (equal to
var.instance_count).
As the number of module instances grows, the number of output retrievals grows the same way.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 output retrievals |
| 100 | 100 output retrievals |
| 1000 | 1000 output retrievals |
Pattern observation: The work grows directly with the number of module instances.
Time Complexity: O(n)
This means the time to get all outputs grows in a straight line as you add more module instances.
[X] Wrong: "Getting outputs from multiple modules happens all at once, so time stays the same no matter how many modules there are."
[OK] Correct: Each module output must be retrieved separately, so more modules mean more work and more time.
Understanding how output retrieval scales helps you design efficient Terraform modules and predict deployment times.
"What if we combined all outputs into a single map inside the module instead of separate outputs? How would the time complexity change?"