Introduction

In my recent AWS class, we had a tricky lab where we had to get back into an EC2 instance after losing the key pair. It seems like tough challenge — like being locked out with no spare key. Everyone was stuck, but somehow, I figured it out.

Problem Statement

You have lost the key pair for an EC2 instance (Vm1) and need to recover access without terminating or rebuilding the instance.

Solution Overview

The process involves creating a new key pair, temporarily accessing the volume of the affected instance, updating SSH keys, and reattaching the volume. Below are the steps for future reference.

1. Create a New Key Pair

Go to the AWS EC2 console. Navigate to Key Pairs and create a new key pair named newKeyPair. Download the private key (.pem file) and save it securely.

2. Launch a Temporary EC2 Instance

Launch a temporary EC2 instance (VM2Temporary) using the newKeyPair. Use the same Availability Zone as Vm1 for compatibility.

3. Stop Vm1 and Detach Its Root Volume

Stop the instance Vm1 from the EC2 console. Navigate to Elastic Block Store (EBS) > Volumes. Detach the root volume of Vm1.

4. Attach the Detached Vm1’s Volume to VM2Temporary Instance

Attach the detached volume as a secondary disk (e.g., /dev/xvdf) to VM2Temporary.

5. Mount the Vm1’s Volume on VM2Temporary

Connect to VM2Temporary via SSH or MobaXterm using newKeyPair and run the following commands:

Run lsblk to Confirm the new disk is attached

Run sudo mkdir -p /mnt/oldVolume to create a new folder inside mnt directory

Run sudo mount -o nouuid /dev/xvdf1 /mnt/oldVolume to mount the attached disk

6. Append the New Public Key

Run sudo cat /home/ec2-user/.ssh/authorized_keys >> /mnt/oldVolume/home/ec2-user/.ssh/authorized_keys to append new public key in authorized_key file of Vm1’s volume.

Pro Tip: You can manually edit the file with nano or vi to avoid duplicate entries.

7. Unmount the Volume

Run sudo umount /mnt/oldVolume to safely detach.

8. Reattach the Volume to Vm1

Detach the volume from VM2Temporary. Reattach it as the root volume (e.g., /dev/xvda) to Vm1.

9. Start Vm1 and Access with New Key Pair

Start Vm1 from the console. Connect using MobaXterm or SSH with newKeyPair.

Summary

After losing access to the EC2 instance Vm1 due to a lost key pair, a new key pair was created, and a temporary instance (VM2Temporary) was launched. Vm1’s root volume was detached, mounted on VM2Temporary, and the new public key was added to its authorized_keys file. The volume was then reattached to Vm1, which then restarted. Access was successfully regained using the new key pair, restoring secure connectivity to the instance.