How to Force Destroy Resource in Terraform
Terraform resource that having lifecycle prevent_destroy = true
can not be destroyed. You need to manually edit the file inplace and change the value prevent_destroy
to false
manually each time you want to destroy the resource. Instead of having to edit manually and make git status dirty we can automate this using simple shell script.
Automate Force Destroy Resource in Terraform
The idea is simple.
- Search all *.tf files and look the value of
prevent_default = true
toprevent_default = false
- Run
terraform destroy
command - Revert the changes back to
prevent_default = true
#!/bin/bash
$ find . -name '*.tf' -type f \
-exec perl -i -pe 's@prevent_destroy = true@prevent_destroy = false@g' {} \;
# Run terraform destroy
[ "$IS_PLAN" = "yes" ] && terraform plan -destroy || terraform destroy $@
# Revert the changes
$ find . -name '*.tf' -type f \
-exec perl -i -pe 's@prevent_destroy = false@prevent_destroy = true@g' {} \;
Save the file with name e.g: terraform-force-destroy.sh. To issue terraform plan -destroy
command use the following.
$ IS_PLAN=yes bash terraform-force-destroy.sh
To force destroy the resource use the following command.
$ bash terraform-force-destroy.sh -auto-approve
You can give normal terraform's arguments just like the original terraform destroy
.
0 comments:
Post a Comment