Remote-exec Provisioner in Terraform: What It Is and How It Works
remote-exec provisioner in Terraform runs commands on a remote machine after the resource is created. It connects via SSH or WinRM to execute scripts or commands directly on the target server, helping automate setup tasks.How It Works
The remote-exec provisioner works like a remote helper that runs commands on a server after Terraform creates it. Imagine you just bought a new appliance and want to set it up immediately. Instead of doing it yourself, you send instructions remotely to configure it. Similarly, Terraform connects to the new machine using SSH (for Linux) or WinRM (for Windows) and runs the commands you specify.
This happens right after the resource is ready, so you can install software, change settings, or start services automatically. It’s like having a remote control to finish the setup without logging in manually.
Example
This example shows how to use remote-exec to run a simple command on an AWS EC2 instance after it launches.
resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" provisioner "remote-exec" { inline = [ "echo 'Hello from Terraform!' > /tmp/terraform.txt" ] connection { type = "ssh" user = "ec2-user" private_key = file("~/.ssh/id_rsa") host = self.public_ip } } }
When to Use
Use the remote-exec provisioner when you need to perform setup tasks on a server right after it is created. This includes installing software, configuring services, or running scripts that prepare the machine for use.
It is helpful when you want to automate manual steps that happen after resource creation without building complex images or external automation tools. For example, you might use it to install a web server, update packages, or start a database service immediately after launching a virtual machine.
Key Points
- Runs commands remotely: Executes scripts on the target machine after creation.
- Uses SSH or WinRM: Connects securely to Linux or Windows servers.
- Automates setup: Helps finish configuration without manual login.
- Not for complex provisioning: Best for simple tasks, not full configuration management.