There are reasons when specific infrastructure is no longer needed. When that infrastructure is managed trough HashiCorp Terraform, the
terraform destroy command can be used to tell Terraform to destroy the resources and then remove it from the Terraform State File (
.tfstate) accordingly. Using this command by itself, without any arguments, will destroy all the infrastructure managed by the Terraform project. However, if the specific Terraform resource is specified using the
-target attribute, then only that particular resource will be destroyed.
Destroy All Resources
Calling the Terraform Destroy command will instruct Terraform to terminate / destroy all the resources managed by the Terraform project. This will enable you to completely tear down and remove all resources defined in the Terraform project that have previously been deployed.
When using this command, you don’t need to delete the Terraform code for the resources from the Terraform project. This is particularly important when needing to “delete” the resources that are managed by the Terraform project, so the Terraform plan and apply can be subsequently run again to recreate the resources that were just deleted.
terraform destroycommand used to delete your Terraform-managed resources from your environment. Be especially careful using this command in Production environments as it can be easy to delete critical resources your organization may need; such as databases or virtual machines.
Destroy Specific Resources
If specific resources managed by Terraform must be terminated / destroyed, but not all of them in the entire project, then the
-target attribute can be used to specify just the resource that is to be destroyed.
terrafrom destroy -target=<terraform-resource> terraform destroy -target=azurerm_virtual_network.hub_vnet
-target attribute will destroy just that single resource in the Terraform project and remove it from the Terraform State File (
.tfstate). All other resources in the Terraform project will remain untouched.
Delete Code to Destroy Resources
If a specific resource defined in the Terraform code is no longer needed, then you can just delete the Terraform code defining the resource from the Terraform project. Once the code is deleted, the next time the Terraform
plan command is executed, it will trigger Terraform to show that resource will be destroyed when the
apply command is executed.
Essentially, removing the Terraform configuration code for a resource from a Terraform project will tell Terraform to destroy that resource the next time the
terrafrom apply command is executed. This provides a simpler way to destroy / terminate resources that are no longer needed through the normal workflow process of deleting the code for that resource from the Terraform project itself.
I hope these tips help you better manage your resources and Terraform projects!