/ mozey.co / blog

ec2 repair key

April 10, 2016

🔗 Replace a lost Key Pair on an EC2 instance

🔗 Stop the instance

🔗 Detach root volume

🔗 Attach root volume to an accessible instance

sudo mkdir /mnt/recovery

sudo mount /dev/xvdf1 /mnt/recovery

🔗 Create new key pair if required

If you still have access to KEY.pem, then see below to re-create public key, otherwise generate a new key pair using email to label it

ssh-keygen -t rsa -C "[email protected]"

🔗 Replace private key

cd /mnt/recovery/home/ubuntu

cp ./.ssh/id_rsa ./.ssh/id_rsa.bak

mv /home/ubuntu/KEY.pem ./.ssh/id_rsa

🔗 Re-create public key from private key

cp ./.ssh/id_rsa.pub ./.ssh/id_rsa.pub.bak

ssh-keygen -y -f ./.ssh/id_rsa > ./.ssh/id_rsa.pub

🔗 Update authorized keys

cat ./.ssh/id_rsa.pub > ./.ssh/authorized_keys

chown ubuntu:ubuntu /mnt/recovery/home/ubuntu/.ssh/authorized_keys

🔗 Re-attach root volume to original instance

sudo umount /mnt/recovery 

Use EC2 Console to attach volume to

/dev/sda1