Skip to content

Instantly share code, notes, and snippets.

@jensendarren
Last active February 19, 2020 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jensendarren/5aa04b463ea8f780ddbe2a095787214c to your computer and use it in GitHub Desktop.
Save jensendarren/5aa04b463ea8f780ddbe2a095787214c to your computer and use it in GitHub Desktop.
Add new SSH Keypair to an EC2 instance when you have lost your .pem file!

How to update your EC2 instance with a new keypair

  1. Create a new keypair in AWS Console

  2. Start a new temporary recovery EC2 instance

  3. Stop the lost keypair instance

  4. Detach the EBS drive from the lost keypair instance

  5. Attach the EBS drive to the recovery EC2 instance (/dev/sdf)

  6. Now SSH into the recovery instance and check the attached EBS drives lsblk -f

  7. Make a new temp directory to mount the attached drive sudo mkdir /mnt/tempvol

  8. Mount the drive to the new temp directory sudo mount /dev/xvdf1 /mnt/tempvol

  9. Copy the authorized_keys file to the location on the mounted drive: cp .ssh/authorized_keys /mnt/tempvol/home/ubuntu/.ssh

  10. Unmount the attached drive: sudo umount /mnt/tempvol

  11. Back in AWS Console, detach the drive from the recovery EC2 instance

  12. Re-Attach to lost keypair instance as /dev/sda1 (so that its a root drive)

  13. Start the lost keypair instance

  14. SSH into the lost keypair instance using your new keypair .pem file

  15. Breath easy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment