Content of first.tf
resource "aws_instance" "ubuntu_zesty" {
ami = "ami-6b7f610f"
instance_type = "t2.micro"
key_name = "myec2key"
}
$ ssh-keygen -f terraform_ec2_key
We now have two files:
$ ls terraform_ec2*
We will need to provision public key, and keep private key safe and hidden:
provider "aws" {
access_key = "AKIAIVBOWPGYHYWPZ2NQ"
secret_key = "${var.secret_key}"
region = "eu-west-2"
}
resource "aws_instance" "ubuntu_zesty" {
ami = "ami-6b7f610f"
instance_type = "t2.micro"
key_name = "terraform_ec2_key"
}
resource "aws_key_pair" "terraform_ec2_key" {
key_name = "terraform_ec2_key"
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDfMCqXraSPxvhL2LIGluGC7Y8UsV1PuMcH1L3u7zdHnMQl0CzAt+1yjqdcbu/OVDBMtoPfimTp5BxawuodDdEEewNSOonL517oSQqwdaunkoy6bioITMvj6iiG4ab3thy0BaT0MWb7Thbf8KDHPIxLm0fdgJHSOhXRb6TEToNCi+zm9BVYcKiYK6HBfnh4wp9CI2pyhZ1OEhly/8K+SjQzg4j8TR/5EH7JEiCl64Y5gXwNxLDyjHHiGMqk2sv6EfxRncroAYVhonG/N63Fkd1BTOIWLNovgId/ehw/+ejh2LHi5Y7+whgPzVqaFfzmhXW/RSRMaAmxeAoLZWDUpeGx kayanazimov@kayanazimov.local"
// public_key = "${file("terraform_ec2_key.pub")}"
}
As you can see we added key_name to aws_instance resource and defined public_key inside aws_key_pair resource,
alternatively you could refer to file as well instead putting contents, it is actually more preferable as less chances to make copy-paste mistake.