06. Provisioners
Provisioners are used to execute scripts on a local or remote machine as part of resource creation or destruction.
Scripts can be executed on resource creation (default) or destruction.
Important: Use provisioners as a last resort. There are better alternatives for most situations.
See: Provisioners syntax
Remote exec
The remote-exec provisioner invokes a script on a remote resource after it is created.
The connection can use ssh or WinRM.
resource "aws_instance" "myec2" { ami = "ami-0ca285d4c2cda3300" instance_type = "t2.micro" key_name = "terraform-key" # default sg used here. Be sure that it allows port 80 and 22 connection { type = "ssh" user = "ec2-user" private_key = file("./terraform-key.pem") host = self.public_ip } provisioner "remote-exec" { inline = [ # Updating with the latest command for Amazon Linux machine "sudo yum install -y nginx", "sudo systemctl start nginx" ] } }
Local exec
The local-exec provisioner invokes a local executable after a resource is created.
resource "aws_instance" "myec2" { ami = "ami-082b5a644766e0e6f" instance_type = "t2.micro" provisioner "local-exec" { command = "echo ${aws_instance.myec2.private_ip} >> ips.txt" } }
→ With the local-exec, the attribute name is command, which is a string.
On destroy
# I agree, this example is a bit silly provisioner "remote-exec" { when = destroy inline = [ "sudo yum -y remove nano" ] }
→ With the remote-exec, the attribute name is inline, which is a list(string).
Failure management
By default, provisioners that fail will also cause the terraform apply itself to fail.
The on_failure setting can be used to change this. The allowed values are:
- continue Ignore the error and continue with creation or destruction.
- fail Raise an error and stop applying (the default behavior)