Assing Key Pair Value to EC2 with Terraform

Semih Üstündağ
1 min readAug 27, 2021

--

Let’s create a new folder to work on, terraform file and a directory for our keys.

$ mkdir -p key-pair-example/keys
$ touch key-pair-example/main.tf

Inside the folder key-pair-example run the command to create our keys.

$ ssh-keygen -q -f keys/terraform-key-pair -C aws_terraform_ssh_key -N ''

Now we can create our terraform file. As a first step we have to provide the plugin, credentials and the region in the main.tf file.

provider "aws" {
profile = "default"
region = "eu-central-1"
}

Now we will use Terraform’s aws_key_pair resource.

resource "aws_key_pair" "terraform_key_pair" {
key_name = "ec2_key_pair"
public_key = file("keys/terraform-key-pair.pub")
}

Let’s use this in our aws_instance resource.

resource "aws_instance" "ec2-with-key-pair" {
ami = "ami-0cc0a36f626a4fdf5"
instance_type = "t2.micro"
key_name = "${aws_key_pair.terraform_key_pair.key_name}"
}

We can now provision our instance and connect it with the private key file.

$ terraform init
$ terraform apply -auto-approve

With auto-approve flag, we don’t have to type yes to confirm.

Do not forget to destroy the resources you create.

$ terraform destroy -auto-approve

--

--