Fjouatte
Fjouatte

Reputation: 155

Destroying specific terraform infrastructure

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 !

Upvotes: 7

Views: 12632

Answers (3)

SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6208

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
  • sometimes a targeted plan/apply/destroy can still encompass additional resources if they depend on each other

Upvotes: 10

Harry Sarshogh
Harry Sarshogh

Reputation: 2197

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"

Upvotes: 3

BMW
BMW

Reputation: 45223

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.

Upvotes: 0

Related Questions