Depends_on for explicit dependencies in Terraform - Time & Space Complexity
When using Terraform, some resources must wait for others to finish before starting. We analyze how this waiting affects the total time taken.
We want to know how adding explicit dependencies changes the number of steps Terraform takes.
Analyze the time complexity of this Terraform code with explicit dependencies.
resource "aws_instance" "app" {
count = var.instance_count
# instance config here
}
resource "aws_eip" "ip" {
count = var.instance_count
depends_on = [aws_instance.app]
# elastic IP config here
}
This code creates multiple instances, then assigns elastic IPs to each, waiting for instances to finish first.
Look at what happens repeatedly when Terraform runs this code.
- Primary operation: Creating each instance and then each elastic IP.
- How many times: Each resource is created once per count, so twice the count in total.
As the number of instances grows, the total operations grow too.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 20 (10 instances + 10 IPs) |
| 100 | 200 (100 instances + 100 IPs) |
| 1000 | 2000 (1000 instances + 1000 IPs) |
Pattern observation: The total operations grow directly with the number of instances, doubling because of the two resource types.
Time Complexity: O(n)
This means the total steps grow in a straight line as you add more instances.
[X] Wrong: "Adding depends_on makes Terraform do extra work that grows faster than the number of resources."
[OK] Correct: depends_on only orders the steps; it does not multiply the number of operations beyond the resources you already create.
Understanding how dependencies affect execution helps you design efficient infrastructure and explain your choices clearly in conversations.
"What if we removed depends_on and let Terraform decide the order? How would the time complexity change?"