Working on a project recently I was faced with the problem of how best to destroy terraform infrastructure. There are a few ways to do it, and the best way depends on what you are actually trying to do.
Note: there are many providers that you can use with Terraform but I’ll be using AWS for these examples. The logic is the same whatever provider you are using.
Remove configuration
One way is to simply remove the resources from the configuration (this could be blocks of code, files, or directories). Then run terraform apply
. The Terraform language is declarative, meaning that it defines the end goal rather than the steps needed to get there. So when you apply the changes it will see that the configuration is gone and will delete the corresponding instances from AWS (or whichever provider you are using). This is best for removing only part of your terraform project.
Terraform destroy
If you want to destroy the whole project then use terraform destroy
. Run it in the root directory then delete the project.
Heads up - you might be tempted to just delete the project without doing terraform destroy
first (like the method above but for the entire project). However if you do this, Terraform won’t be able to tell AWS you’ve deleted that config so the infrastructure won’t be torn down. You would have to go to the AWS console and remove the instances manually, defeating the point of having Infrastructure as Code.
Destroy with a target
If you want to use the destroy command to tear down only part of your infrastructure, then use a target:
terraform destroy -target="aws_instance.example[0]"
The advantage here is that it’s easy to bring the resources back (just do terraform apply
again). However to remove it permanently remember to delete the related config from the code! Otherwise, the next time you terraform apply
the resources will be recreated.
Replacing an instance
You could even use this method of destroying and applying again to replace an instance (for example if the hardware is degraded).
However the recommended way to do this is by using the -replace
option with terraform apply
.
terraform apply -replace="aws_instance.example[0]"
I hope you found this explanation helpful, feel free to leave a comment below!
Top comments (0)