0
0
TerraformConceptBeginner · 3 min read

Remote-exec Provisioner in Terraform: What It Is and How It Works

The 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.

terraform
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
    }
  }
}
Output
Terraform creates the EC2 instance and then connects via SSH to run the command, creating a file /tmp/terraform.txt with the text 'Hello from Terraform!' on the instance.
🎯

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.

Key Takeaways

The remote-exec provisioner runs commands on a remote machine after resource creation.
It connects using SSH for Linux or WinRM for Windows to execute scripts or commands.
Use it to automate simple setup tasks like installing software or starting services.
It is not meant for complex configuration management or long-term automation.
Always ensure secure connection details like private keys are handled safely.