1
votes

I want to use a terraform script to create an ec2 instance. I want also to be able to connect to the machine using SSH and a key-pair created in the AWS console.

This is the relevant portion of the script:

resource "aws_instance" "web" {
  instance_type = "t2.micro"
  ami = "${lookup(var.aws_amis, var.aws_region)}"

  key_name = "${var.key_name}" # this is my keypair
  connection {
    type = "ssh"
    user = "${var.ssh_user}"
  }
  vpc_security_group_ids = ["${aws_security_group.default.id}"]
  subnet_id = "${aws_subnet.default.id}"
  provisioner "remote-exec" {
    inline = [
      "sudo apt-get -y update"
    ]
  }
}

Then, after 5 minutes a get a timeout indicating that terraform could not connect to the ec2 instance

aws_instance.web: Still creating... (5m20s elapsed)
aws_instance.web (remote-exec): Connecting to remote host via SSH...
aws_instance.web (remote-exec):   Host: 34.250.66.198
aws_instance.web (remote-exec):   User: ubuntu
aws_instance.web (remote-exec):   Password: false
aws_instance.web (remote-exec):   Private key: false
aws_instance.web (remote-exec):   SSH Agent: true
Error applying plan:

1 error(s) occurred:

* aws_instance.web: 1 error(s) occurred:

* timeout

However, even if terraform files with a timeout

  • All the resources are actually created successfully
  • I am able to list them on the AWS console
  • I'm able to manually connect through SSH + pem file to the instance without any issue (even before the timeout error): ssh -i "aws.pem" ubuntu@instance_ip

This information might be relevant: * terraform version: v0.10.7 * region: eu-west-1 * OS: El Capitan 10.11.6

Just in case this is how i'm mapping the amis

variable "aws_amis" {
  default = {
    eu-west-1 = "ami-674cbc1e"
    us-east-1 = "ami-1d4e7a66"
    us-west-1 = "ami-969ab1f6"
    us-west-2 = "ami-8803e0f0"
  }
}

Thanks a lot for your help

1
At which point do you supply the private ssh key to terraform?Dusan Bajic

1 Answers

1
votes

You need to specify the private key in the connection, something like this:

provisioner "remote-exec" {
    inline = [
        "sudo apt-get -y update"
    ]
    connection {
        private_key = "${file("/location/of/the/pem/file")}"
    }
}