Dependency inversion with modules in Terraform - Time & Space Complexity
We want to understand how the time to apply Terraform changes grows when using modules that depend on each other.
Specifically, how does adding more modules affect the number of operations Terraform performs?
Analyze the time complexity of this Terraform module dependency setup.
module "network" {
source = "./modules/network"
}
module "database" {
source = "./modules/database"
depends_on = [module.network]
}
module "app" {
source = "./modules/app"
depends_on = [module.database]
}
This sequence shows three modules where each depends on the previous one, creating a chain of dependencies.
Look at what Terraform does repeatedly when applying this setup.
- Primary operation: Terraform plans and applies each module in order, waiting for dependencies to finish.
- How many times: Once per module, but each module waits for the previous one to complete.
As you add more modules in a chain, Terraform must process each one after the previous finishes.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 3 | 3 (one per module) |
| 10 | 10 (one per module) |
| 100 | 100 (one per module) |
Pattern observation: The number of operations grows directly with the number of modules.
Time Complexity: O(n)
This means the time to apply grows linearly as you add more modules in a dependency chain.
[X] Wrong: "Adding more modules won't affect apply time because Terraform runs everything in parallel."
[OK] Correct: When modules depend on each other, Terraform waits for one to finish before starting the next, so time adds up.
Understanding how dependencies affect execution time helps you design efficient infrastructure and explain your choices clearly.
"What if all modules were independent with no depends_on? How would the time complexity change?"