Terraform state rm for removing resources - Time & Space Complexity
We want to understand how the time to remove resources from Terraform state grows as we remove more resources.
Specifically, how does the number of resources affect the work Terraform does when running terraform state rm?
Analyze the time complexity of removing multiple resources from Terraform state.
terraform state rm aws_instance.example1 aws_instance.example2 aws_instance.example3
This command removes multiple specific resources from the Terraform state file in a single operation.
Each terraform state rm command:
- Primary operation: Reads the state file, searches for the resource(s), removes them, and writes the updated state back.
- How many times: Once per command, regardless of the number of resources removed in that command.
The dominant operation is reading and writing the state file for each command.
As the number of resources to remove increases, the number of times Terraform reads and writes the state file depends on how many commands you run.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 (one by one) | 10 reads and 10 writes |
| 10 (all at once) | 1 read and 1 write |
| 100 (one by one) | 100 reads and 100 writes |
| 100 (all at once) | 1 read and 1 write |
Pattern observation: The work grows with the number of commands, not just the number of resources removed.
Time Complexity: O(n) if removing resources one by one (n commands), but O(1) if removing all resources in a single command.
This means the time to remove resources grows linearly with how many commands you run, not necessarily how many resources you remove.
[X] Wrong: "Removing multiple resources one by one is just as fast as removing them all at once."
[OK] Correct: Each removal command reads and writes the state file separately, so doing many removals one by one takes more time than doing them together in one command.
Understanding how operations scale with input size helps you plan efficient infrastructure changes and shows you think about real-world impacts of your commands.
What if we removed multiple resources in a single terraform state rm command? How would the time complexity change?