Skip to content

The key_pairs.tf File

Filename Location Group Project/Repository
key_pairs.tf ./key_pairs.tf infrastructure terraform

Why?

We'll publish a public key to AWS, an EC2 Key Pair, and use this to SSH into instances and manage them via Ansible. Without defining a Key Pair in AWs we'll be able to manage or access our instances.

Note

If you use the wrong SSH public key then you'll be locked out of your EC2 Instances. You'll have to recreate the instances if you get the key wrong and have to change it to the correct one.

Breakdown

1
2
3
4
resource "aws_key_pair" "httpcats" {
  key_name   = "deployment-key"
  public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCx0zxU998xfSDPJsqmVr4xm1sOwC5H8MI5pU3EJTqv3jbZcbA79rS5Jb68cvKg2yc5a+GzJkSN88xyGEurw0BTjNH/saDWSepC8t3LaIrhDj8CYByLtBWznVvYfkBrUi2psUOUeCMUpXLbDR8uEdq7/EghME02iLZZcj8e3MtpR4wul3heLjvDN9XN6qxq8CG1Uy+P8aBnX6yAy55kZyZeWlpCjilFCy64zcJU+RjVzS8zURsV+hV8hLo9oQYnzA7ETvEyAZvQ7sBne3iK8Bs5l3yvZKnFnhlM2Soo1XUHm/HXt5sGTnf/IGkFLbL5mIUW9riZ1EtMa1DdnHTarHive1nwDQp4muRg+6FJS2xXV9bHrtzkY+1u0gG2mvyGVETLqxOIUN8NRfu6L/1vdtfN44XSVq5lVfWl79RZ+owKoTnKl+E63kSNfEiFf9V3edul3ttzhOHOr46ZVzbkOVds9xOv/oaItvCS6LB33dtFvXsGcuncEnT9gMGRBSOsVyk="
}

The contents of deployment_key.pub are what you need to provide for the above code to work. This means you have to update the public_key attribute of the aws_key_pair to be the contents of your public key, not mine.

You can get these contents by using cat:

1
cat ~/.ssh/deployment_key.pub

Warning

Remember that the file deployment_key is the private key and should not be shared with anyone!

Grab the contents of the file and copy/paste them into the public_key attribute.

The Solution

1
2
3
4
resource "aws_key_pair" "httpcats" {
  key_name   = "deployment-key"
  public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCx0zxU998xfSDPJsqmVr4xm1sOwC5H8MI5pU3EJTqv3jbZcbA79rS5Jb68cvKg2yc5a+GzJkSN88xyGEurw0BTjNH/saDWSepC8t3LaIrhDj8CYByLtBWznVvYfkBrUi2psUOUeCMUpXLbDR8uEdq7/EghME02iLZZcj8e3MtpR4wul3heLjvDN9XN6qxq8CG1Uy+P8aBnX6yAy55kZyZeWlpCjilFCy64zcJU+RjVzS8zURsV+hV8hLo9oQYnzA7ETvEyAZvQ7sBne3iK8Bs5l3yvZKnFnhlM2Soo1XUHm/HXt5sGTnf/IGkFLbL5mIUW9riZ1EtMa1DdnHTarHive1nwDQp4muRg+6FJS2xXV9bHrtzkY+1u0gG2mvyGVETLqxOIUN8NRfu6L/1vdtfN44XSVq5lVfWl79RZ+owKoTnKl+E63kSNfEiFf9V3edul3ttzhOHOr46ZVzbkOVds9xOv/oaItvCS6LB33dtFvXsGcuncEnT9gMGRBSOsVyk="
}

Terraform Documentation

Type Documentation
aws_key_pair Terraform AWS Provider

Committing the Code

  1. Set your working directory to the infrastructure/terraform repository
  2. Save the file as key_pairs.tf and use git add key_pairs.tf to add it to the Git staging area
  3. Use git commit -am 'defining the public key for ssh access to our instances' to commit the file to our repository
  4. Push the code to GitLab.com: git push

Last update: August 29, 2021