Remote Execution Example
Below is an example using our familiar web server scenario. In this configuration, an inline script is executed after an EC2 instance is deployed. This script updates the package index, installs NGINX, and then enables and starts the service:Ensure that the proper network connectivity (SSH for Linux or WinRM for Windows), security groups, and an SSH key pair are in place for successful execution.
Remote Execution with Connection Block
This example expands on the previous one by including a connection block, which specifies the SSH details required to connect to the remote instance. The connection block leverages theself.public_ip expression to dynamically reference the deployed instance’s public IP address:
Local Execution with local-exec Provisioner
Provisioners are not limited to remote tasks. The local-exec provisioner is used to execute commands on the local machine where Terraform is run. This is particularly useful for gathering information and saving it locally. The following example stores the public IP address of an EC2 instance in the/tmp/ips.txt file:
Create-Time and Destroy-Time Provisioners
By default, provisioners run after a resource is created (create-time provisioners). However, you can also configure a provisioner to run before a resource is destroyed (destroy-time provisioners) using thewhen argument. The example below demonstrates both scenarios:
Handling Provisioner Failures
A key behavior of provisioners is that if the command or script execution fails, the entireterraform apply operation will error out. For example, specifying an incorrect file path can lead to failure:
on_failure argument within the provisioner block. This allows Terraform to continue with resource creation even if the command fails. For example:
Use provisioners sparingly. They are intended as a last resort when native resource configurations are not available.