Change AWS EC2 Instance Key Pair without stopping the Instance

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

Written by 

Sidharth is a Lead Consultant, having experience of more than 4.5 years. He has started working on Scala and Clojure and is actively involved in other developmental work. He enjoys working in a team and believes that knowledge is something that should be shared openly and on a large scale. As an avid gamer and passionate player, he likes to be involved in both indoor and outdoor activities.

Leave a Reply

%d bloggers like this: