Losing the private SSH key to your Amazon EC2 instance on Amazon Web Services (AWS) can be a daunting experience. However, AWS provides several methods to regain access to your instance. This guide will walk you through the steps needed to recover your EC2 instance on AWS when your private SSH key is lost.

Steps to Recover Access to Your EC2 Instance on AWS

  1. Stop the Affected EC2 Instance on AWS
    • Navigate to the EC2 Dashboard in the AWS Management Console.
    • Select the instance you need to regain access to and click on “Instance State” and then “Stop Instance”.
  2. Detach the Root Volume
    • When the instance is stopped, select “Actions” and then “Instance Settings” followed by “Detach Volume.”
    • Confirm the detachment of the root volume.
  3. Attach the Volume to Another EC2 Instance on AWS
    • Launch a new EC2 instance or use an existing one in the same Availability Zone.
    • Attach the detached volume from the affected instance to this new instance as a secondary volume.
    • Navigate to “Actions” -> “Attach Volume,” select the volume, and specify the new instance’s ID.
  4. Modify the Volume’s SSH Configuration
    • SSH into the new instance using its private key.

Mount the attached volume. For example, if the volume is attached as /dev/xvdf, you can mount it with:

sudo mkdir /mnt/recovery

sudo mount /dev/xvdf1 /mnt/recovery

Navigate to the mounted directory:

cd /mnt/recovery/home/ec2-user/.ssh

Add your new public key to the authorized_keys file:

echo “your-new-public-key” >> authorized_keys

  1. Reattach the Volume to the Original Instance

Unmount the volume:

sudo umount /mnt/recovery

  • Detach the volume from the new instance and reattach it to the original instance as the root volume.
    • Select “Actions” -> “Detach Volume”.
    • Select “Actions” -> “Attach Volume” and attach it to the original instance as /dev/xvda.
  1. Start the Original Instance on AWS
    • Navigate back to the EC2 Dashboard, select the original instance, and click “Instance State” -> “Start Instance”.
    • You should now be able to SSH into your instance using the new private key.

Additional Tips

  • Create AMIs: Regularly create Amazon Machine Images (AMIs) of your instances on AWS to ensure you have backups.
  • Use Systems Manager: AWS Systems Manager can manage instances without SSH access.
  • Rotate Keys Regularly: Regularly rotate your SSH keys and ensure they are securely stored.

Following these steps, you can regain access to your EC2 instance on Amazon Web Services (AWS) even if you’ve lost your private SSH key. Always remember to keep your SSH keys secure and consider using AWS IAM roles and AWS Systems Manager to minimize such risks in the future.