Terraform not only helps us in infrastructure creation and management but also in provisioning them during resource creation or deletion.
Provisioners are used to execute scripts or shell commands on a local or remote machine as part of resource creation or deletion.
Provisioners can be used to bootstrap a resource, cleanup before destroy, run configuration management etc.
Below are list of the supported provisioners
- chef : The chef provisioner installs, configures and runs the Chef Client on a remote resource.
- connection : The chef provisioner to define or override connection properties of a resource
- file : The file provisioner is used to copy files or directories to the newly created resource.
- habitat : The habitat provisioner installs the Habitat supervisor and loads configured services.
- local-exec : The local-exec provisioner invokes a local executable after a resource is created.
- null_resource : The null_resource is a resource that allows you to configure provisioners that are not directly associated with a single existing resource.
- remote-exec : The remote-exec provisioner invokes a script on a remote resource after it is created.
- salt-masterless : The salt-masterless Terraform provisioner provisions machines built by Terraform using Salt states, without connecting to a Salt master.
Defining a Provisioner
To define a provisioner, add a provisioner block within the resource block. Multiple provisioner blocks can be added to define multiple provisioning steps.
resource "aws_instance" "webserver" { ami = "ami-b374d5a5" instance_type = "t2.micro" provisioner "local-exec" { command = "echo ${aws_instance.webserver.public_ip} > ip_address.txt" } }
Running Provisioners
Provisioners by default run only when a resource is created, not during updating or any other lifecycle.
If a creation-time provisioner fails, the resource is marked as tainted. A tainted resource will be planned for deletion and recreation upon the next terraform apply.
Failure Behavior
By default, provisioners that fail will cause to error. With on_failure setting we can change this.
The allowed values are:
- continue : Ignore the error and continue with creation or destruction.
- fail (default behavior): Error. If it is a creation provisioner, taint the resource.
resource "aws_instance" "webserver" { # ... provisioner "local-exec" { command = "echo ${server.private_ip} > file.txt" on_failure = "continue" } }
Destroy Provisioners
Provisioners can also be defined that run only during a destroy operation. These are useful for performing system cleanup, extracting data, etc.
If when = “destroy” is specified, the provisioner will before the resource is destroyed.
resource "aws_instance" "web" { # ... provisioner "local-exec" { command = "echo Creating" } provisioner "local-exec" { when = "destroy" command = "echo Destroying" } }