Create EC2 Keypair

Overview

A key pair, consisting of a public key and a private key, is a set of security credentials that you use to prove your identity when connecting to an Amazon EC2 instance.

In other words, an AWS Key Pair is a pair of public and private keys call ssh key. It can be generated by AWS (as we will do) or you can generate it using the ssh-keygen command and then upload it to AWS. AWS will then help you add the public key to the ~/.ssh directory of the correct instance you are using.

Steps

The command below is used to create an EC2 keypair for the lab:

Create a keypair using the aws ec2 create-key-pair command. This command will return the content of the key file, then save it to a file with a *.pem format for later use.

However, to use this key file, you need to configure its permissions

chmod 400 key.pem

❓ Why chmod 400
When connecting to an EC2 instance via SSH, the private key file (*.pem) needs to have tightly configured access permissions to ensure security (1 condition to become an ssh key is to only allow the owner to access and use it). The chmod 400 key.pem command sets the permissions of the key file to be readable only by the owner (400 = 100 000 000), ensuring that no other users on the system can access it (except root user 😁 and the owner). This is necessary because SSH will refuse to use a private key file that other users can access.

ecs_instance_key_name=$project-keypair
# Create keypair
aws ec2 create-key-pair \
    --key-name $ecs_instance_key_name \
    --region $region \
    --tag-specifications `echo 'ResourceType=key-pair,Tags=['$tagspec` \
    --query 'KeyMaterial' \
    --output text > ./$ecs_instance_key_name.pem

Execution

  1. Create Keypair

    Create Keypair

  2. Check the keypair on the AWS Console

    Keypair created