Change AWS EC2 Instance Key Pair without stopping the Instance

Knoldus Inc.
Knoldus - Technical Insights
2 min readMar 29, 2018

If you landed on this blog post then I guess you might be looking for a way to change the Key pair associated with your AWS EC2 Instance without stopping the instance or you’re just following our blog posts :) Either way, I’ll try to explain the easiest way to do just that in this blog post.

Let’s start by creating a new Key pair which can be easily done from AWS EC2 console from “Key Pairs” section under “Network & Security”. I’ve attached a screenshot for reference purpose

key-pairs

From inside “Key Pairs” option create a new Key pair and as soon as it is created it’ll be downloaded from your browser to your machine.

Now use the following command to generate the ssh-rsa from your pem file

ssh-keygen -f KEY.pem -y

This will generate an output which you can save for the purpose of using it later on your EC2 instance for which the Key pair has to be changed.

You might want to change the permissions of your PEM file before running the above command which can be done using

chmod 600 KEY.pem

Once this is done, SSH to your EC2 instance using the old PEM file and add your new ssh-rsa to the authorized_keys file. The authorized_keys file is usually located in .ssh folder at the root of the Linux user but that depends on the AMI you’re using.

Usual location of authorized_keys

/home/YOUR_USER/.ssh/authorized_keys

Don’t forget to remove your old ssh-rsa from the authorized_keys file if that is what you want.

knoldus-advt-sticker

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com