AWS – Creating a key pair

Install PHP on CentOS 8

A key pair is used to access your instances via SSH. Key pairs are an integral part of asymmetrical cryptography and are an encryption technique that makes use of two non-identical keys to encrypt and decrypt data. A user’s public key can be shared freely, and data that is encrypted with the public key can only be decrypted with the private key. When you create a key pair with EC2, the key can be associated with any number of instances, and you download a .pem file, which is similar to a .ppk file in Putty or an id_rsa file on Linux machines.

Getting ready

To complete this recipe, you must have your AWS CLI tool configured correctly. Follow the guidance in Chapter 1, AWS Fundamentals, to configure your CLI.

How to do it…

Follow these steps to create and download a key pair:

  1. Create the key pair and save it to disk, as follows:
Note that this is intended to be a secret key and must be protected accordingly! Don’t store the key in a public place.
  aws ec2 create-key-pair \
        --key-name MyEC2KeyPair \
        --query 'KeyMaterial' \
        --output text > ec2keypair.pem

  1. Change the permissions on the created file:
chmod 400 ec2keypair.pem

How it works…

This call requests a new private key from EC2. The response is then parsed using a JMESPath query, and the private key (in the KeyMaterial property) is saved to a new key file with the .pem extension. The public key is stored in the region so that it can be copied to new EC2 instances. You cannot copy keys from region to region, and you cannot retrieve the full key pair after initial creation.

Finally, we change the permissions on the key file so that it cannot be read by other users – this is required before SSH will allow you to use it.

Comments are closed.