Terraform – Destroy Command

Terraform destroy command, is a way to destroy the infrastructure created using Terraform.

Often we need to destroy all or specific resources that we are managing using the terraform. terraform destroy is a way we can destroy the managed resource.

Syntax

terraform destroy <options> <resource_id>

To delete all managed resources, we can directly use the command, You will prompt for confirmation prior to destroying the managed resources.

Option 1:

terraform destroy

As we can see in the below output, terraform will list the resources to be destroyed and will prompt for confirmation.

Note: The confirmation should be case sensitive “yes“, any other word or even “Yes/YES” etc will result in cancellation of destruction.

terraform destroy command

Option 2:

To destroy specific resources from your managed resource use the flag –target along with the destroy command.

Syntax

terraform destroy --target <resource_id>

If you are not aware of your <resource_id>, there is an easy way to get the resource id. you will need to run the state list command. The state list command will list all the resources under your state file.

terraform state list

Once you have the resources listed, copy the resource id and use it in your destroy command as the target resource.

terraform destroy --target aws_vpc.siva_terraform_vpc[0]
terraform destroy command -target

If you do not want a user prompt/confirmation for resource deletion, you will need to pass the flag –auto-approve.

Syntax

terraform destroy --auto-approve
terraform destroy command –aoto-approve

As we can see all the resources will get terminated without any user confirmation.

Often we may want to delete all resources, except a few. In such a case, we can use the terraform state rm command to remove the resource from the state file and then run the terraform destroy command.

Syntax

terraform state rm <resource_id>
terraform state rm aws_vpc.siva_terraform_vpc[0]
terraform destroy command state rm

Now, if you run the terraform destroy command, all resources except the one we have removed from the state file will get terminated as terraform will not consider the resource as managed by terraform.

Read further,
Terraform Destroy

Terraform Destroy

  • Destroy command will be used to destroy the created configuration.
  • You can use target flag to specify which resource you want to delete.
  • $ terraform  destroy – target < flagname>
  • You can also pass the -out flag to pass the output to a file.
  • $ terraform destroy –out <filename.tfplan>