wardviaene / terraform-course

Course files for my Udemy course about Terraform

Home Page:https://www.udemy.com/learn-devops-infrastructure-automation-with-terraform/?couponCode=TERRAFORM_GIT

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error while using public and private keys to connect to AWS

vkarry opened this issue · comments

I am seeing following error, when terraform is trying to use private key to connect to instances in AWS. Please advise.

$ terraform plan

Error: aws_instance.example: 1 error(s) occurred:

  • aws_instance.example: file: open MyKey: no such file or directory in:

${file("${var.path_to_private_key}")}

Here is the snippet from instance.tf which is executing:
resource "aws_key_pair" "mykey" {
key_name = "MyKey"
public_key = "${file("${var.path_to_public_key}")}"
}

resource "aws_instance" "example" {
ami = "${lookup(var.amis,var.region)}"
instance_type = "t2.micro"
key_name = "${aws_key_pair.mykey.key_name}"
tags {
Name = "${var.instance_tag}"
}
provisioner "file" {
source = "script.sh"
destination = "/tmp/script.sh"
}
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/script.sh",
"sudo /tmp/script.sh"
]
}
connection {
user = "${var.instance_username}"
private_key = "${file("${var.path_to_private_key}")}"
}
}

And variables.tf:
variable "path_to_public_key" {
description = "Path to public key"
default = "MyKey.pub"
}

variable "path_to_private_key" {
description = "Path to private key"
default = "MyKey"
}

Never mind. I fixed this issue by providing file extension ".pem" to public key file.

Hi Vkarry,
can you know the file format and change you have made and i have the issue related to plan.
Error: Error applying plan:

1 error(s) occurred:

  • aws_instance.example: Failed to read key " Public key

Hello Master !

The instance is created. However, the script.sh does not run. How to resolve this issue?
Here is the file
##################################################
resource "aws_key_pair" "Mykey" {
key_name = "Mykey"
public_key = file(var.PATH_TO_PUBLIC_KEY)
}

resource "aws_instance" "example" {
ami = var.AMIS[var.AWS_REGION]
instance_type = "t2.micro"
key_name = aws_key_pair.Mykey.key_name

provisioner "file" {
source = "script.sh"
destination = "./tmp/script.sh"
}
provisioner "remote-exec" {
inline = [
"chnodv +x /tmp/script.sh",
"sudo ./tmp/script.sh",
]
}
connection {
host = coalesce(self.public_ip,self.private_ip)
type = "ssh"
user = var.INSTANCE_USERNAME
private_key = file(var.PATH_TO_PRIVATE_KEY)
}
}

##########################################################

"Mykey" is created in AWS, however, it is not download to SSH folder. Therefore, the folder has no keys (Private as well as Public) at all for the "remote-exec"

Here is the error message:
Error: timeout - last error: SSH authentication failed (unbutu@34.201.37.56:22): ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain