Terraform apply -replace flag - Time & Space Complexity
When using Terraform's -replace flag, we want to understand how the time to apply changes grows as we replace more resources.
We ask: How does replacing resources affect the number of operations Terraform performs?
Analyze the time complexity of applying Terraform with the -replace flag on multiple resources.
terraform apply -replace=module.example.resource[0] \
-replace=module.example.resource[1] \
-replace=module.example.resource[2]
This command forces Terraform to destroy and recreate the specified resources during apply.
Terraform performs these repeated operations for each replaced resource:
- Primary operation: Destroy and recreate the specified resource via API calls.
- How many times: Once per resource listed with
-replace.
As you increase the number of resources to replace, Terraform makes more API calls to destroy and recreate each one.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | About 10 destroy and 10 create calls |
| 100 | About 100 destroy and 100 create calls |
| 1000 | About 1000 destroy and 1000 create calls |
Pattern observation: The number of operations grows directly with the number of replaced resources.
Time Complexity: O(n)
This means the time to apply changes grows linearly with how many resources you replace.
[X] Wrong: "Replacing multiple resources happens all at once, so time stays the same."
[OK] Correct: Each resource replacement requires separate destroy and create operations, so time grows with the number of replacements.
Understanding how Terraform operations scale helps you plan infrastructure changes efficiently and communicate clearly about deployment times.
"What if we replaced a module with many resources at once instead of individual resources? How would the time complexity change?"