← All Posts

How to Recover AWS EC2 Instance Without Key Pair (Manual + Automated DevOps Guide)

Lost your EC2 .pem key? Learn how to recover AWS EC2 access manually and automate the process using AWS CLI like a DevOps engineer.

Lost your AWS EC2 .pem key? You’re locked out — but not stuck. This guide covers both manual recovery and automation.

Manual EC2 Recovery#

Step 1: Stop Instance Stop your EC2 instance from AWS console.

Step 2: Detach Root Volume Go to EBS → Volumes → Detach root volume.

Step 3: Attach to Another Instance Attach as /dev/xvdf.

Step 4: Mount Volume

Terminal window
sudo mkdir /mnt/ec2-recovery
sudo mount /dev/xvdf1 /mnt/ec2-recovery

Step 5: Update SSH Key

Terminal window
cd /mnt/ec2-recovery/home/ec2-user/.ssh/
sudo nano authorized_keys

Step 6: Reattach & Start Reattach volume and start instance.#

Automated DevOps Approach Stop Instance

Terminal window
INSTANCE_ID=i-xxxxxxxx
aws ec2 stop-instances --instance-ids $INSTANCE_ID
aws ec2 wait instance-stopped --instance-ids $INSTANCE_ID

Get Volume ID

Terminal window
VOLUME_ID=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" --output text)

Detach Volume

Terminal window
aws ec2 detach-volume --volume-id $VOLUME_ID
aws ec2 wait volume-available --volume-ids $VOLUME_ID

Attach to Helper

Terminal window
HELPER_ID=i-helper123
aws ec2 attach-volume --volume-id $VOLUME_ID --instance-id $HELPER_ID --device /dev/xvdf

Inject Key

Terminal window
sudo mount /dev/xvdf1 /mnt/recovery
echo "YOUR_PUBLIC_KEY" | sudo tee -a /mnt/recovery/home/ec2-user/.ssh/authorized_keys
sudo umount /mnt/recovery

Reattach

Terminal window
aws ec2 detach-volume --volume-id $VOLUME_ID
aws ec2 wait volume-available --volume-ids $VOLUME_ID
aws ec2 attach-volume --volume-id $VOLUME_ID --instance-id $INSTANCE_ID --device /dev/xvda

Start Instance

Terminal window
aws ec2 start-instances --instance-ids $INSTANCE_ID

Final Verdict Manual recovery works. Automation scales. Use SSM instead of SSH keys for long-term stability.