Replace SSH Key pair on Amazon EC2

If you want to revoke your EC2 command line access to a team member, or you find yourself in a situation where your SSH private key has fallen into someone else’s hands, you should immediately secure your EC2 instance. In this mini tutorial, I will show you how to replace your SSH key pair and secure your EC2 instance.

Step 1: Login to your AWS console

Replace SSH Key pair on Amazon EC2 1
Login to your AWS Console

Step 2: Go to your EC2 Dashboard and Select Key Pairs

Replace SSH Key pair on Amazon EC2 2
Click on Key Pairs from your EC2 Dashboard

You can also select Key Pairs under Network and Security on the menu on the left.

Step 3: Delete old key

Replace SSH Key pair on Amazon EC2 3
Select the old key and click on Delete

Tread carefully on this section. If you have a number of key pairs, you want to select the one you want to remove. If, by accident, you delete the wrong key, there is no need to worry. You have only deleted the private key from your AWS console. The old private key saved on your computer still works. The only difference this time that you cannot reuse the same key when launching a new instance.

Step 4: Create a fresh private key

Replace SSH Key pair on Amazon EC2 4
Generate a fresh private key from your console

Name your key, and AWS will generate a fresh private key and download it in .pem format on your local machine.

Step 5: Generate the public key from your local SSH client

Replace SSH Key pair on Amazon EC2 5
Generate Public Key from your local machine

Now open your terminal and use the following command

ssh-keygen -y -f /path_to_key_pair/my-key-pair.pem

Your should get a code that starts with ssh-rsa. This is your public key which you will place it on your instance. Copy it!

Step 6: Login to your instance with the old private key

Connect to your EC2 instance with your old private key.

Step 7: Copy and paste the public key on the SSH authorized keys file

Navigate to .ssh directory where you will find .authorized_keys file. Open it using nano or vi.

nano .authorized_keys

Remove the old public key and paste the current public key you generated from your local machine.

Exit your instance and login again with your new private key.

If you login successfully, congrats! You have secured your EC2 instance.

Reference:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#delete-key-pair

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts