A remote provisioner executes commands or scripts on a machine reached through Terraform. The remote-exec provisioner runs on that machine, unlike local-exec, which runs wherever Terraform runs. section 10.3.2
Configure remote execution around three practical concerns:
- Provide a connection block, commonly using SSH credentials, a user, and the target host. Connections can route through a SOCKS5 proxy or bastion host. section 10.3.1
- Choose exactly one remote-exec input mode per provisioner: script uploads one file, scripts uploads and runs files in order, and inline supplies commands directly. section 10.3.2
- Use provisioner order deliberately. A remote-exec command can create a directory before a file provisioner uploads a directory, or set permissions and start a service afterward. section 10.3.3
- Remember that the connection need not belong to the resource being provisioned; for example, a DNS record can connect to an instance specified separately. section 10.3.1
Install software and configure a remote instance
Attach an SSH connection to an instance, then run inline package commands, upload an installation script, or run installation and configuration scripts sequentially. For larger setup tasks, keep scripts in the module rather than embedding every command in Terraform.
Listing 10.13 The remote-exec provisioner
resource "aws_instance" "main" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
connection {
type = "ssh"
user = "ubuntu"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
provisioner "remote-exec" { #1
inline = [ #2
"sudo apt-get update",
"sudo apt-get install -y nginx"
]
}
provisioner "remote-exec" { #3
script = "${path.module}/scripts/install.sh" #4
}
provisioner "remote-exec" {
scripts = [ #5
"${path.module}/scripts/install.sh",
"${path.module}/scripts/configure.sh"
]
}
}
Compare inline commands with single-script and ordered multi-script remote execution in a complete Terraform resource. section 10.3.2
