Connection Types for remote-exec Provisioner in Terraform

Terraform Remote-Exec Connection Types

In Terraform, the remote-exec provisioner allows us to execute scripts on a remote resource after it’s been created. The connection to the remote resource can be established using different connection types. The primary connection types supported by Terraform are:

1. SSH (Secure Shell) Connection

Description: This is the most common method used for Linux and other Unix-like systems. It involves using SSH to connect to the remote machine.

Parameters:

  • host: The IP address or hostname of the target resource.
  • port: The port on which the SSH service is running, typically port 22.
  • user: The username used to connect to the remote machine.
  • password: The password for the SSH connection (optional, not recommended for security reasons).
  • private_key: The private key used for authentication.
  • agent: Boolean value indicating if the SSH agent should be used for authentication.
  • bastion_host: The IP address or hostname of a bastion (jump) host if the target resource is behind a firewall.

Example:

resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" provisioner "remote-exec" { connection { type = "ssh" user = "ec2-user" private_key = file("~/.ssh/id_rsa") host = self.public_ip } inline = [ "sudo apt-get update", "sudo apt-get install -y nginx" ] } }

2. WinRM (Windows Remote Management) Connection

Description: This method is used for connecting to Windows-based systems, typically using the WinRM protocol.

Parameters:

  • host: The IP address or hostname of the target resource.
  • port: The port on which the WinRM service is running, typically port 5985 (HTTP) or 5986 (HTTPS).
  • user: The username used to connect to the remote machine.
  • password: The password for the WinRM connection.
  • use_ssl: Boolean indicating whether to use HTTPS (SSL).
  • https: Deprecated in favor of use_ssl.
  • insecure: Boolean indicating whether to skip SSL certificate validation.
  • ntlm: Boolean indicating whether to use NTLM for authentication.

Example:

resource "aws_instance" "example" { ami = "ami-87654321" instance_type = "t2.micro" provisioner "remote-exec" { connection { type = "winrm" user = "Administrator" password = "Password1234" host = self.public_ip use_ssl = false } inline = [ "powershell.exe Install-WindowsFeature Web-Server", "powershell.exe Start-Service W3SVC" ] } }

3. None (Local Execution)

Description: In some cases, the remote-exec provisioner can be used locally if you don’t need a remote connection. This is useful for running local commands on the Terraform host machine itself, often as a local-exec provisioner instead.

Summary

  • SSH is the go-to connection type for Unix-like systems.
  • WinRM is used for Windows-based systems.
  • We can also avoid remote connections by executing commands locally, typically with a local-exec provisioner.