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):

#cloud-boothook
#!/bin/bash

SSH_PUBKEY="ssh-rsa
AAAAB3NzaC1yc2EAAAADAQABAAABgQCf5C5DQwLJXnBNUIE/FeuEmPS0WqVKwCl2hemyoESNUhnsxPwfz17+wjT/AduShkqmeVd+qLJi/rxKJBWAQZuTk6bc8kVabT1VzH7Jls1zcDXo3VHkN1udTidXMSoyPc3Xzez4LrnJqNzsEDf/wXurFP3FSQwLDe+DWJWXha0a8hBKCBSWdavsJwDEZTUQWbLMH9i2pZE4Z65yT5YO/T1J5b4BkUapcOzbYKP7SxiWkhpPvda9xB5wzmO9o3IgpsHIi5gs2M4eYHGH3YSyIkFxI0M97W0KjrkLqi+iOkeeOaaOdJFSBL0EAmh0LsojSoDlts9vBoLX8F5JeXtt4HyUHMuIqFMxP+FpwZIoAiQybfR71xu8/SJX0U8LfdU1eFgfncK6+yCIDGLt8MKV7sHSbIzZtBaTVXGFiMREtu/UcyOu4qWludx1ui17WGX0B2K9xREU/DRhVQWweIMJdLMXVFuA7qTQdy/IYZ+W7Uu1k9NPXI4+y584olXL3ILpTN8="

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.