Replacing SSH keys on running instances

As part of your regular security practices or in the event an employee leaves your company you should be switching out the SSH keys on your servers.

This is an easy process but if not done correctly you can unintentionally lock your self out of your servers.

You should start by generating a new SSH key pair which on Ubuntu is as simple as running the ssh-keygen tool and following the prompts.

Once you have your newly created private and public keys you should SSH to the server you wish to change with your old key.

Copy the contents of the new public key you created with ssh-keygen – it will be the .pub file –  and put them on a new line in the ~/.ssh/authorized_keys file.

You should now have at least two entry’s in this file one will be the public key for your old SSH key and one will be for your new SSH key, save this file and disconnect from the server.

Now its time to test your new SSH key, connect to the server with your new key like so:

If you have added the public key correctly you should be able to logon to the server, you can now edit the authorized_keys file once more and remove the entry for the old public key you are discarding. Save the file once more and disconnect and reconnect to ensure things are working as expected.

As a final step you should try connecting to the server with your old SSH key, this should now no longer work, resulting in the following message:

One thought on “Replacing SSH keys on running instances”

Leave a Reply

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