How can re-access to EC2 instance
I hope it never happens to them
Some time ago I lost/deleted the .pem file (I don’t really know) to access one of my EC2 instances, it was a productive instance and the only person with access was me.
Tried several ways without success. After a while I started to create a new EC2 instance and configure the deploy to that new instance, since the code was safe in a rep, the public resources in an S3 and the DB in an RDS, therefore my plan was “move” everything to that new instance and after a couple of hours everything would be fine, but something in my mind told me that it was not correct and that “something” could be lost if I lowered the instance and raised another… that something It was tricky: there were trusted certificates, configuration of payment method integrations, “hardcoded” integrations that were only inside EC2 and never supported (badly there) anywhere else… so I kept looking and found the following solution (finally).
Error: Authentication failed, permission denied
Solution: Use a userdata script and add the SSH public key to the authorized_keys file to regain access
How?
- On our computer we obtain the ssh public key and “save / copy” its content for the future.
- Go to AWS, find the instance and stop it.
- We go to Actions, Instance Settings, Edit User Data and paste the following content replacing the OS_USER with the username associated with the AMI from which you launched the instance and the PUBLIC_SSH_KEY with our ssh public key from the step
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
- //
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
-[scripts-user, always]
- //
Content-Type:
text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
OS_USER=@@@@@@
chown root:root /home
chmod 755 /home
chown $OS_USER:$OS_USER /home/$OS_USER -R
chmod 700 /home/$OS_USER
chmod 700 /home/$OS_USER/.ssh
chmod 600 /home/$OS_USER/.ssh/authorized_keys
echo '$PUBLIC_SSH_KEY' >> /home/$OS_USER/.ssh/authorized_keys
chown $OS_USER:$OS_USER/ home/$OS_USER -R
- //
Restart the instance and now you can access :)
At last, to delete this “file” you just have to go to where you edited it (step 3) and delete its content :)
I hope this helps you as much as it does me