Resetting your AWS EC2 keypair

[blog poststandalone]

I had to access to an AWS EC2 instance but all I got was access to the AWS Management Console. No KeyPair (a.k.a. SSH Public Key) so no way to access via SSH. Also the EC2 Instance Connect which should allow to connect to the instance via a browser-based SSH connection.

I started looking for information and this AWS support article was the only think I found and... it did not work, of course.

Any other article mentioned methods that didn't really work either. So I investigated a bit more and finally got it, but I was so frustrated that this was so hard to find that I had to write a post about it.

First of all, for this method to work, you will need to stop the instance so it is important to understand the implications of this. If the instance is not using persistent storage you could lose data when you stop it. In my case it was using EBS or Elastic Block Storage so I didn't had to worry about it.

The rescue here is to use what is called the instance User Data, which allows to configure or execute things in the instance in several configurable situations.

So here are the steps:

  1. Stop the instance.

  2. Select the instance and then click on Actions >> Instance Settings >> View/Change User Data.

  3. Here you can add code to be executed in the next boot like this (replacing SSH_PUBKEY with your key):



sed -i 's/^PermitRootLogin .*/PermitRootLogin without-password/g' /etc/ssh/sshd_config
systemctl restart sshd.service

mkdir -p /root/.ssh
chmod 700 /root/.ssh

printf '\n%s\n' "$SSH_PUBKEY" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
  1. Start the instance.

  2. Check via ssh that you have access

  3. Stop the instance again.

  4. Remove the User Data that you added so it does not run again each time the instance boots.

  5. Start the instance.

I hope this is helpful to anybody that faces the same problem.