Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - Delete all resources except one

I have a Terraform 0.11 project with 30-40 different resources. I would like to delete all of them except a few - and those few are logically related to each other.

I was looking for something close to terraform destroy --except=resource-id but that of course doesn't exist.

Is there a way to achieve that without too much scripting (Terraform admins have various OSs)? Would using modules make that process easier perhaps?

like image 661
rath Avatar asked Mar 20 '19 16:03

rath


People also ask

How do you destroy all resources except one in Terraform?

Step 4 – Destroy All Except a FewRemove the resource from the state file using terraform state rm command. Run terraform destroy – without --target argument. After successful destruction, import the target resources back in the state file.

How do I skip resource deletion in Terraform?

Prevent resource deletion To prevent destroy operations for specific resources, you can add the prevent_destroy attribute to your resource definition. This lifecycle option prevents Terraform from accidentally removing critical resources. Add prevent_destroy to your EC2 instance.

How do you ignore a resource in Terraform?

When you want Terraform to ignore changes between subsequent apply commands you can use the lifecycle ignore_changes meta-argument. The ignore_changes argument means that Terraform will set the value when the resource is first deployed and then forever ignore any changes to it.

Is the Terraform destroy command the only way to destroy resources?

The 'destroy' command terraform destroy only destroys the infrastructure for the current project. There are no changes made to the resources allocations running elsewhere.


1 Answers

There is no exist feature in terraform destroy command currently. If you really want to do that, and you know what you do, here is the workaround.

# list all resources terraform state list  # remove that resource you don't want to destroy # you can add more to be excluded if required terraform state rm <resource_to_be_deleted>   # destroy the whole stack except above excluded resource(s) terraform destroy  

So why do these commands work for your idea?

The state (*.tfstate) is used by Terraform to map real world resources to your configuration, keep track of metadata.

terraform state rm cleans a record (resource) from the state file (*.tfstate) only. It doesn't destroy the real resource.

Since you don't run terraform apply or terraform refresh, after terraform state rm, terraform doesn't know the excluded resource was created at all.

When you run terraform destroy, it has no detail about that excluded resource’s state and will not destroy it. It will destroy the rest.

By the way, later you still have chance to import the resource back with terraform import command if you want.

like image 161
BMW Avatar answered Sep 28 '22 12:09

BMW