In the previous example, we created an EC2 instance, which we wouldn’t be able to access, that is because we neither provisioned a new key pair nor used existing one, which we could see from the state report:

Program 1 - XXXXXX

If you already have a key pair which you are using to connect to your instance, which you will find in EC2 Dashboard, NETWORK & SECURITY – Key Pairs:

Content of first.tf


resource "aws_instance" "ubuntu_zesty" {
  ami           = "ami-6b7f610f"
  instance_type = "t2.micro"
  key_name = "myec2key"
}

Program 2 - XXXXXX

Now, let’s say you don’t have any keys, or you just want to provision a new key just for this EC2 instance. Let’s destroy our instance first:

$ 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.