Reputation: 189
I am trying to use terraform destroy
in my bash script so that I can automatically destroy my resources from the current state file. But I don't want to ask users variables again while destroying, I want it to automatically take the variables from the current state file and destroy it. How can this be achieved?
Upvotes: 1
Views: 798
Reputation: 56877
Assuming you don't actually care about state values as you are just destroying what's there and none of the variables are relied on to destroy things as is normally the case then you don't actually need to read the state, just set some dummy value for these required variables.
You could set dummy values for each of the unset variables that would normally be prompted for on the command line:
for variable in $(grep -R -I 'variable .* {}' path/to/terraform/files/directory | grep -v -F .terraform/ | cut -d'"' -f2 | sort -u); do
export TF_VAR_$variable=dummy
done
This will find all the variables that are unset (assuming you have defined these as variable "foo" {}
as terraform fmt
will output) in all .tf
files in your directory. It will then exclude the matches in the .terraform
directory so it doesn't do anything with child modules that may have been pulled in. And then it find the variable key that is inside double quotes and then deduplicates these.
After it has found all the unset, required variables it then exports these Terraform variables as environment variables as TF_VAR_$variable=dummy
so that each variable is set.
Upvotes: 1