Creation-Time Provisioners
Creation-time provisioners are triggered when a resource is created. Terraform supports both remote and local execution of commands during this phase. For instance, the example below launches an AWS EC2 instance and uses the local-exec provisioner to record the instance’s public IP address to a local file:Remember to verify that the specified file path exists and is writable by your user.
Destroy-Time Provisioners
Terraform also allows you to execute provisioners right before a resource is destroyed. By setting thewhen argument to destroy, you can define commands to be executed during the resource’s teardown process. The example below shows a resource block that contains both creation and destroy-time provisioners:
Handling Provisioner Failures
By default, if a provisioner fails, Terraform stops the execution and the entireterraform apply fails. For example, if the command in the creation-time provisioner attempts to write to a non-existent directory, Terraform will produce an error:
terraform apply with this configuration may produce an output similar to:
Ensure that any file paths or commands used in provisioners are valid and tested. Failing provisioners can block your deployment process.
Allowing Provisioner Failures
In some cases, the execution of a provisioner may be optional and should not halt the entire apply process if it fails. To override the default behavior, set theon_failure argument to continue:
on_failure option set to continue, Terraform proceeds with the apply process even if the provisioner fails: