How to rotate a Key Pair on an AWS instance

This is something I don’t have to do too often but if your company has policies on key rotation then this might be useful.

I’m assuming you already have the ability to ssh onto your current EC2 instance with an existing key pair you created in AWS.  

This will walk you through creating a new key pair in AWS and getting it applied to that instance and removing the old key pair from the instance.

The first step is to ssh on to the instance that you want to replace the key on.

The second step is to login to your AWS console and go to the EC2 service.

Click on the Key Pairs menu item on the left side.

Click Create Key Pair and go through the steps to create a new key pair and download it to your  computer.

On the command line type the following to get the public key from the AWS Key Pair you created:

ssh-keygen -f your_download_key.pem -y

It should produce something like this:

 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDq8nNujE18FYcBOz3w6M2wDzvmYgHaAreK3QqCAOXCo/UGS1wBNY/KCQvQRSkpZvNVlv26P/4KhlEArwq75cqpFwejcdsDgVMaUoAE6DzotuaLa+cGUxuMXcSYsebyYGZtJMZKlXHrme9Qxb3+95aC291KbEHpzuoNreScKg/qEqu6W2dDZRsdL9GT2uJA5b3kT7fszKjTNbZaaeTdWrOMdpnrA+ZZm7izHt5c0wWnoIOrnYk6G+xEsdSSKnmtRKMdtH6OPXBSrfGG0V16D8PAVk466DXu7plztmdSZnSDKnaRveJhZPcBnANPmOuLnCYZ/jR3qYkARSwlV1yDbyId

Copy this output to your clipboard.

Go back to your EC2 instance and edit(via vi or your favorite editor) ~/.ssh/authorized_keys .

Go to the bottom of the file and paste the new public key info from your clipboard and save the file.

Try using the new key to ssh onto the instance.

If it works, you are good to go and you can delete the old key pair from AWS if you are sure you don’t need it anywhere else.

One item to note on the AWS console’s EC2 instance screen is that the Key Pair name will remain as the old key pair name since there is no way to update that metadata.  If you are afraid you will forget the key pair name you used, you might try adding a tag with the key pair name.