Bird
Raised Fist0
Terraformcloud~10 mins

Connection blocks for SSH in Terraform - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Connection blocks for SSH
Define resource requiring SSH
↓
Add connection block with SSH details
↓
Terraform uses SSH to connect
↓
Run remote commands or provisioners
↓
Close SSH connection
↓
Resource provisioned
Terraform uses connection blocks to specify SSH details, enabling it to connect to remote machines and run commands during provisioning.
Execution Sample
Terraform
resource "null_resource" "example" {
  connection {
    type        = "ssh"
    host        = "192.168.1.10"
    user        = "ubuntu"
    private_key = file("~/.ssh/id_rsa")
  }

  provisioner "remote-exec" {
    inline = ["echo Hello from Terraform"]
  }
}
This Terraform code connects via SSH to a remote machine and runs a simple echo command.
Process Table
StepActionSSH Connection DetailsProvisioner CommandResult
1Start resource creationNot connected yetNo command runWaiting to connect
2Read connection blocktype=ssh, host=192.168.1.10, user=ubuntu, key=~/.ssh/id_rsaNo command runReady to connect
3Establish SSH connectionConnected to 192.168.1.10 as ubuntuNo command runSSH session open
4Run provisioner commandSSH session activeecho Hello from TerraformCommand executed successfully
5Close SSH connectionDisconnectedNo command runSSH session closed
6Resource creation completeNo connectionNo command runResource provisioned
💡 SSH connection closed after running provisioner commands; resource creation finished.
Status Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
connection.typeundefinedsshsshsshssh
connection.hostundefined192.168.1.10192.168.1.10192.168.1.10192.168.1.10
connection.userundefinedubuntuubuntuubuntuubuntu
connection.private_keyundefined~/.ssh/id_rsa~/.ssh/id_rsa~/.ssh/id_rsa~/.ssh/id_rsa
ssh_sessionclosedclosedopenopenclosed
provisioner.command_statusnot runnot runnot runsuccesssuccess
Key Moments - 3 Insights
Why does Terraform need the private_key in the connection block?
Terraform uses the private_key to authenticate the SSH connection securely, as shown in step 2 of the execution_table where the key is read before connecting.
What happens if the SSH connection fails at step 3?
If SSH connection fails, Terraform cannot run the provisioner commands and resource creation will stop or error out, as the SSH session must be open to proceed.
Why is the SSH session closed after running commands?
Terraform closes the SSH session after running provisioner commands to free resources and maintain security, as seen in step 5 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the SSH connection status at step 3?
ANot connected yet
BDisconnected
CConnected to 192.168.1.10 as ubuntu
DConnection failed
💡 Hint
Check the 'SSH Connection Details' column at step 3 in the execution_table.
At which step does Terraform run the remote command?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Provisioner Command' and 'Result' columns in the execution_table.
If the private_key path is incorrect, what will most likely happen?
ASSH connection will fail at step 3
BProvisioner command runs successfully
CSSH session closes immediately at step 2
DResource creation completes without SSH
💡 Hint
Refer to the importance of private_key in the connection block and step 3 connection establishment.
Concept Snapshot
Terraform connection blocks specify how to connect to remote machines.
Use type = "ssh", host, user, and private_key to set SSH details.
Terraform opens SSH, runs provisioner commands, then closes connection.
This enables remote configuration during resource creation.
Full Transcript
Terraform uses connection blocks to connect to remote machines via SSH. The connection block includes the SSH type, host IP, username, and private key path. Terraform reads these details, opens an SSH session, runs any remote commands defined in provisioners, then closes the SSH connection. This process allows Terraform to configure resources on remote servers securely and automatically during deployment.

Practice

(1/5)
1. What is the main purpose of a connection block in Terraform when using SSH?
easy
A. To specify the Terraform backend storage
B. To define how Terraform connects to remote machines for running commands or copying files
C. To configure the cloud provider credentials
D. To create a new SSH key pair automatically

Solution

  1. Step 1: Understand the role of connection blocks

    Connection blocks specify how Terraform connects to remote machines, typically using SSH, to run commands or transfer files during provisioning.
  2. Step 2: Differentiate from other configurations

    SSH key creation, cloud credentials, and backend storage are configured elsewhere, not in connection blocks.
  3. Final Answer:

    To define how Terraform connects to remote machines for running commands or copying files -> Option B
  4. Quick Check:

    Connection block purpose = Define SSH connection [OK]
Hint: Connection blocks set SSH details for remote commands [OK]
Common Mistakes:
  • Confusing connection block with SSH key creation
  • Mixing connection block with cloud provider config
  • Thinking connection block manages backend storage
2. Which of the following is the correct syntax to specify an SSH connection block in Terraform?
easy
A. connection { type = "winrm" user = "ubuntu" host = self.public_ip private_key = file("~/.ssh/id_rsa") }
B. connection { protocol = "ssh" username = "ubuntu" address = self.public_ip key = file("~/.ssh/id_rsa") }
C. connection { ssh_user = "ubuntu" ssh_host = self.public_ip ssh_key = file("~/.ssh/id_rsa") }
D. connection { user = "ubuntu" host = self.public_ip private_key = file("~/.ssh/id_rsa") }

Solution

  1. Step 1: Recall Terraform connection block syntax

    The correct keys are user, host, and private_key. The type key is not required for SSH as it is the default.
  2. Step 2: Identify the valid syntax

    connection { user = "ubuntu" host = self.public_ip private_key = file("~/.ssh/id_rsa") } uses correct keys without unnecessary or incorrect ones like type or protocol.
  3. Final Answer:

    connection { user = "ubuntu" host = self.public_ip private_key = file("~/.ssh/id_rsa") } -> Option D
  4. Quick Check:

    Correct keys = user, host, private_key [OK]
Hint: Use user, host, private_key keys in connection block [OK]
Common Mistakes:
  • Adding unnecessary 'type' or 'protocol' keys
  • Using wrong key names like ssh_user or username
  • Omitting required keys like user or host
3. Given this Terraform snippet, what will happen when Terraform tries to connect?
connection {
  user = "admin"
  host = aws_instance.example.public_ip
  private_key = file("~/.ssh/id_rsa")
  timeout = "2m"
}
medium
A. Terraform will connect but ignore the timeout setting
B. Terraform will fail because timeout must be a number, not a string
C. Terraform will connect using SSH as user 'admin' with a 2-minute timeout
D. Terraform will connect using default user instead of 'admin'

Solution

  1. Step 1: Analyze connection block fields

    The block correctly sets user, host, private_key, and timeout. Timeout accepts a duration string like "2m".
  2. Step 2: Understand Terraform SSH connection behavior

    Terraform uses these values to connect via SSH as user 'admin' with a 2-minute timeout for connection attempts.
  3. Final Answer:

    Terraform will connect using SSH as user 'admin' with a 2-minute timeout -> Option C
  4. Quick Check:

    Timeout string '2m' is valid duration [OK]
Hint: Timeout accepts duration strings like '2m' for SSH connections [OK]
Common Mistakes:
  • Thinking timeout must be numeric only
  • Assuming default user is used ignoring 'user' key
  • Believing timeout is ignored by Terraform
4. Identify the error in this Terraform connection block:
connection {
  user = "ec2-user"
  host = aws_instance.web.public_ip
  private_key = "~/.ssh/id_rsa"
}
medium
A. private_key should use file() function to read the key content
B. host should be a static IP, not a resource attribute
C. user must be 'ubuntu' for AWS instances
D. Missing 'type = "ssh"' in connection block

Solution

  1. Step 1: Check private_key value type

    The private_key must contain the actual key content, not just the file path string. Using file("~/.ssh/id_rsa") reads the key content.
  2. Step 2: Validate other fields

    Host can be a resource attribute, user can be 'ec2-user' for Amazon Linux, and 'type' defaults to SSH so it's optional.
  3. Final Answer:

    private_key should use file() function to read the key content -> Option A
  4. Quick Check:

    private_key needs file() to read key [OK]
Hint: Use file() to load private_key content, not just path string [OK]
Common Mistakes:
  • Assigning private_key a file path string directly
  • Assuming host cannot be a resource attribute
  • Forcing user to 'ubuntu' regardless of OS
5. You want to run a remote command on an AWS instance using Terraform. Which connection block setup is best practice to ensure a reliable SSH connection?
hard
A. connection { user = "ec2-user" host = aws_instance.app.public_ip private_key = file("~/.ssh/id_rsa") timeout = "5m" agent = true }
B. connection { user = "ec2-user" host = aws_instance.app.public_ip private_key = file("~/.ssh/id_rsa") timeout = "1m" agent = false }
C. connection { user = "ec2-user" host = aws_instance.app.private_ip private_key = file("~/.ssh/id_rsa") timeout = "5m" agent = true }
D. connection { user = "ubuntu" host = aws_instance.app.public_ip private_key = file("~/.ssh/id_rsa") timeout = "30s" agent = false }

Solution

  1. Step 1: Choose correct user and host

    For AWS Amazon Linux, user is usually 'ec2-user'. Public IP is needed for SSH from outside the VPC.
  2. Step 2: Set appropriate timeout and agent

    A longer timeout like "5m" helps with slow connections. Using SSH agent forwarding (agent = true) can improve key management.
  3. Step 3: Compare options

    connection { user = "ec2-user" host = aws_instance.app.public_ip private_key = file("~/.ssh/id_rsa") timeout = "5m" agent = true } uses correct user, public IP, sufficient timeout, and enables agent forwarding, matching best practices.
  4. Final Answer:

    connection { user = "ec2-user" host = aws_instance.app.public_ip private_key = file("~/.ssh/id_rsa") timeout = "5m" agent = true } -> Option A
  5. Quick Check:

    Public IP, correct user, timeout 5m, agent true = best practice [OK]
Hint: Use public IP, correct user, 5m timeout, and agent true for reliability [OK]
Common Mistakes:
  • Using private IP when public IP is needed
  • Setting too short timeout causing failures
  • Disabling agent forwarding unnecessarily
  • Using wrong user for the OS
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard