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.

vim /data/home/ubuntu/.ssh/authorized_keys

Finish up
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.

--

--

--

I work as a software developer with years of experience within the field of web, apps and server architecture.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Which GPU database is right for me?

Apache Hive: Replication Policy Scheduling

DAY 4: ANDELA BOOT CAMP

A complete implementation guide to Trusted Web Activity(TWA)- OYO Lite (PWA on PlayStore)

The Doors Of Perception (A Ruby Faker Gem Parody)

Data encapsulation in Swift

My journey to learn Python — Day 5

SPRING DATA JPA

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rasmus Styrk

Rasmus Styrk

I work as a software developer with years of experience within the field of web, apps and server architecture.

More from Medium

Let’s install a VPN with PiVPN

Automate your SSH logins with this .bat script for your private network.

Copying files to and from remote server using ssh

type in terminal: man scp

VMware NSX-T and Ansible