1
votes

I am getting an error message like below when I run terraform plan

Error: Error in function call

  on instance.tf line 3, in resource "aws_key_pair" "mykey":
   3:   public_key = "${file("${var.PATH_TO_PUBLIC_KEY}")}"
    |----------------
    | var.PATH_TO_PUBLIC_KEY is "mykey.pub"

Call to function "file" failed: no file exists at mykey.pub.

On file system, I have the below two files

/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pem
/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pub

My terraform code is below main.tf

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.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 = [
      "chmod +x /tmp/script.sh",
      "sudo /tmp/script.sh"
    ]
  }
  connection {
    host = "${self.public_ip}"
    user = "${var.INSTANCE_USERNAME}"
    private_key = "${file("${var.PATH_TO_PRIVATE_KEY}")}"
  }
}

vars.tf

variable "AWS_ACCESS_KEY" {}
variable "AWS_SECRET_KEY" {}
variable "AWS_REGION" {
  default = "ap-southeast-2"
}
variable "AMIS" {
  type = "map"
  default = {
    ap-southeast-2 = "ami-039bb4c3a7946ce19"
    ap-southeast-2 = "ami-039bb4c3a7946ce19"
    ap-southeast-1 = "ami-05c6d22d98f97471c"
  }
}

/*
variable "PATH_TO_PRIVATE_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pem"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pub"
}
*/
variable "PATH_TO_PRIVATE_KEY" {
  default = "mykey"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "mykey.pub"
}

variable "INSTANCE_USERNAME" {
  default = "ubuntu"
}

In My AWS Account, I have private Key and I have downloaded public of name Ravi-TF-Work.pem I converted *.pem to *.pub by the command below:

ssh-keygen -y -f private_key1.pem > public_something_else.pub

Terraform version below

Terraform v0.12.5
+ provider.aws v2.20.0

I am confused at this stage with Private Key which is in my AWS account and the public key which I have downloaded (pem file, converted to pub file) and how to get this working.

Any lead would be greatly appreciated.

1

1 Answers

0
votes

You seem to have commented out the location of your actual keys:

/*
variable "PATH_TO_PRIVATE_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pem"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pub"
}
*/
variable "PATH_TO_PRIVATE_KEY" {
  default = "mykey"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "mykey.pub"
}

Uncomment them and delete the dummy definitions:

variable "PATH_TO_PRIVATE_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pem"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "/home/ec2-user/ravi-tf-work-3/Ravi-TF-Work.pub"
}