I lost my ssh key for my Amazon EC2 instance
Yeah, that’s kind of a bad thing to do.
This article helps you to get back into your instance. This was for an Ubuntu instance and it took me like 5 minutes.
It’s a good idea to create a snapshot of the instance first — just in case things go wrong.
Shut down your instance
Remember to reserve the ip or you will get a new one once it boots back up
Detach the root volume
Go to volumes and find the volume attached to instance. Right click and select “detach volume”
Start a Recovery Instance
Simply spin up a new instance of same type, name it RecoveryInstance. A micro instance will do. Choose a key pair that you know works.
Attach the old volume
Once the instance is running attach the old volume to the new instance.
When the volume is attached you can ssh into the RecoveryInstance and mount it.
sudo mkdir /data
sudo mount /dev/xvdf /data
Add your key
What i did was to add my public key to the mounted drive.
Now you got your public key added to the old instance volume. So now we just need to unmount, detach the volume and spin up the old ec2 again.
sudo umount /data
Go back to amazon console and detach the volume. Attach it back to the original instance (remember to set mount point to /dev/sda1 since that is root).
Spin up the old instance and ssh back into it. You can now safely terminate the Recovery Instance and you are done.
Amazon also has another tool (System Manager) for doing some this automatically but i have not tried it yet.