Skip to content

Instantly share code, notes, and snippets.

@tamoyal
Last active January 15, 2023 22:06
Show Gist options
  • Save tamoyal/1b7ec4d3871b343d353d to your computer and use it in GitHub Desktop.
Save tamoyal/1b7ec4d3871b343d353d to your computer and use it in GitHub Desktop.
Transitioning your pem/key on an EC2 instance

Note: This is mainly useful for instances you are essentially locked out of in the case where you don't want to create a new instance.

  1. Launch a micro instance with your new key (we'll call this the "key transitioning instance"). This instance will need to be in the same availability zone ("us-east-1b", for example) as the instances you are locked out of.
  2. Make sure you can ssh in
  3. Select the instance you are locked out of and make note of the attached EBS volume ID which will look something like vol-6a844e25 and the Root Device which will look something like /dev/sda1.
  4. Stop the EC2 instance you are locked out of
  5. Go to that instance's Root Device EBS volume and detach it
  6. Re-attach the EBS volume to the key transitioning instance
  7. On the key transitioning instance, run sudo fdisk -l
  8. Note the "Device" column output from this command that is similar to the "Attachment information" which is displayed when you select the EBS volume (we'll use /dev/xvdf1 as an example). That will be your device name.
  9. Make a mount point sudo mkdir /mnt/tmp
  10. Mount the device sudo mount /dev/xvdf1 /mnt/tmp
  11. Copy your new SSH key to the mounted dir: sudo cp ~/.ssh/authorized_keys /mnt/tmp/home/ubuntu/.ssh/authorized_keys. IMPORTANT: this will overwrite the existing authorized keys. You may want to append the key if that suits your use case.
  12. Unmount the volume sudo umount -d /dev/xvdf1
  13. Detach the volume from the key transitioning instance in the AWS interface
  14. Re-attach it to the original instance and be sure you specify the Device that the original instance expects as the root you noted in step #3
  15. Start the old instance and you should be able to ssh in with the new key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment