Destroying specific terraform infrastructure

Viewed 5987

I created infrastructure for different environment (testing / prod) with terraform using workspaces, locals and -backend-config so there is only two differents files, others files are common for both environment.

Unfortunately, I don't find a way to destroy specific environment the same way (without creating lots of specific files for each environment).

Am I missing something ? Is there a way do that ?

Any help would be appreciated.

Thanks in advance !

Regards,

Florent

EDIT : Thanks for answers, I managed to do what I wanted to do using workspaces, locals and backend-config !

3 Answers

You can use -target to target specific resources to destroy.

terraform destroy \
  -target 'module.default.aws_autoscaling_group.one' \
  -target 'module.default.aws_autoscaling_group.two'

Notes

  • quotations are required around the targets if using count or for_each logic which results in square brackets in the target names.
  • single quotations are better since a for_each would return a double quoted key which would need to be escaped if surrounding the target with double quotes

Don't mix terraform commands init/workspace to plan/apply/destroy.

so I guess you run with below commands to set the backend (where the tfstate files are saved)

terraform init -backend-config=<path>
terraform get
terraform workspace select <env>

Then you should run below commands with same -var-file=<file> or -var 'foo=bar' option for all plan, apply and destroy commands.

terraform plan -var-file=dev/terraformtfvars -var 'foo=bar'
terraform apply -var-file=dev/terraformtfvars -var 'foo=bar'
terraform destroy -var-file=dev/terraformtfvars -var 'foo=bar'

Let me know if this explains your concerns or not.

Using Terraform V 0.13

I have tried to pass tfvars file to destroy command like this:

terraform destroy -auto-approve -var-file="env/stage.tfvars"
Related