Why can't terraform SSH in to EC2 Instance using supplied example?

You have two possibilities:

  1. Add your key to your ssh-agent:

    ssh-add ../.ssh/terraform
    

    and use agent = true in your configuration. The case should work for you

  2. Modify your configuration to use the key directly with

    secret_key = "../.ssh/terraform"
    

    or so. Please consult the documentation for more specific syntax.


I had the same issue and I did following configurations

connection {
    type = "ssh"
    user = "ec2-user"
    private_key = "${file("*.pem")}"
    timeout = "2m"
    agent = false
}

Below is a complete and stand-alone resource "null_resource" with remote-exec provisioner w/ SSH connection including the necessary arguments supported by the ssh connection type:

  • private_key - The contents of an SSH key to use for the connection. These can be loaded from a file on disk using the file function. This takes preference over the password if provided.

  • type - The connection type that should be used. Valid types are ssh and winrm Defaults to ssh.

  • user - The user that we should use for the connection. Defaults to root when using type ssh and defaults to Administrator when using type winrm.

  • host - The address of the resource to connect to. This is usually specified by the provider.

  • port - The port to connect to. Defaults to 22 when using type ssh and defaults to 5985 when using type winrm.

  • timeout - The timeout to wait for the connection to become available. This defaults to 5 minutes. Should be provided as a string like 30s or 5m.

  • agent - Set to false to disable using ssh-agent to authenticate. On Windows the only supported SSH authentication agent is Pageant.

resource null_resource w/ remote-exec example code below:

resource "null_resource" "ec2-ssh-connection" {
  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y python2.7 python-dev python-pip python-setuptools python-virtualenv libssl-dev vim zip"
    ]

    connection {
      host        = "100.20.30.5"  
      type        = "ssh"
      port        = 22
      user        = "ubuntu"
      private_key = "${file(/path/to/your/id_rsa_private_key)}"
      timeout     = "1m"
      agent       = false
    }
  }
}