Hello,
I would like to write a custom script that will be called using the local exec resource. If I run a terraform apply it will run the script with a set of parameters and if I run terraform destroy it will run with different parameters to delete. Is it possible to reference a variable that might know which command I am using?
Hi @david10,
terraform destroy
is largely just a shorthand for terraform apply -destroy
, which creates a plan in the special “destroy mode” and then applies that plan. The destroy planning mode forces Terraform to propose a “delete” action for anything that is currently tracked, ignoring whether it exists in the configuration.
The specific command being run is not something you can program with directly – Terraform CLI and the Terraform language are two distinct parts of the system that work largely independently – but for provisioners in particular you can specify whether each one should run either during a create action or during a destroy action using the when
argument in your provisioner
block:
provisioner "local-exec" {
# with no "when" argument, the provisioner is
# for create-time.
}
provisioner "local-exec" {
# Setting "when" to "destroy" makes this instead
# run when the object is being destroyed.
when = destroy
}
There’s more information on this in Destroy-time Provisioners.
Please note that provisioners are a last resort and so there might be another better way to solve your underlying problem, without using provisioner
blocks at all.