0
0
Terraformcloud~5 mins

Connection blocks for SSH in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
When Terraform needs to connect to a remote server to run commands or copy files, it uses connection blocks. These blocks tell Terraform how to connect using SSH, like giving it the server address, username, and key. This helps automate tasks on remote machines.
When you want Terraform to run setup commands on a new virtual machine after creating it.
When you need to copy configuration files from your local machine to a remote server during deployment.
When you want to automate software installation on a remote server using Terraform.
When you manage infrastructure that requires secure SSH access for provisioning.
When you want to avoid manual SSH login and automate remote tasks in your Terraform scripts.
Config File - main.tf
main.tf
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/id_rsa")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo yum update -y",
      "sudo yum install -y httpd",
      "sudo systemctl start httpd",
      "sudo systemctl enable httpd"
    ]
  }
}

This Terraform file creates an AWS EC2 instance.

The connection block tells Terraform how to connect to the instance using SSH:

  • type: specifies SSH connection.
  • user: the username to log in as.
  • private_key: the SSH private key file used for authentication.
  • host: the IP address of the instance to connect to.

The provisioner "remote-exec" runs commands on the remote server after creation.

Commands
This command initializes the Terraform working directory. It downloads necessary provider plugins and prepares Terraform to run.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
This command creates the AWS EC2 instance and uses the connection block to SSH into it and run the setup commands automatically.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Still creating... [10s elapsed] aws_instance.example: Creation complete after 20s [id=i-0abcd1234efgh5678] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
-auto-approve - Automatically approves the apply without asking for confirmation
This command removes the AWS EC2 instance and cleans up all resources created by Terraform.
Terminal
terraform destroy -auto-approve
Expected OutputExpected
aws_instance.example: Destroying... [id=i-0abcd1234efgh5678] aws_instance.example: Destruction complete after 10s Destroy complete! Resources: 1 destroyed.
-auto-approve - Automatically approves the destroy without asking for confirmation
Key Concept

If you remember nothing else from this pattern, remember: connection blocks tell Terraform how to securely SSH into remote machines to run commands or copy files during provisioning.

Common Mistakes
Not specifying the correct SSH user in the connection block.
Terraform cannot log in to the remote server if the username is wrong, causing connection failures.
Use the correct username for the server, like 'ec2-user' for Amazon Linux or 'ubuntu' for Ubuntu servers.
Using the wrong path or permissions for the private key file.
Terraform fails to authenticate if the private key is missing, unreadable, or has incorrect permissions.
Ensure the private key file exists, is readable, and has secure permissions (e.g., 600). Use the full path or '~/.ssh/id_rsa'.
Not using the instance's public IP or hostname in the host field.
Terraform cannot connect if it tries to use a private IP or an undefined host.
Use 'self.public_ip' or a valid reachable IP address or DNS name for the host in the connection block.
Summary
Use a connection block in Terraform to define how to SSH into remote servers.
The connection block includes user, private key, host, and connection type.
Terraform uses this connection to run commands or copy files during provisioning.