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
sudo mkdir /mnt/ec2-recovery
sudo mount /dev/xvdf1 /mnt/ec2-recovery
Step 5: Update SSH Key
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
INSTANCE_ID=i-xxxxxxxx
aws ec2 stop-instances --instance-ids $INSTANCE_ID
aws ec2 wait instance-stopped --instance-ids $INSTANCE_ID
Get Volume ID
VOLUME_ID=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" --output text)
Detach Volume
aws ec2 detach-volume --volume-id $VOLUME_ID
aws ec2 wait volume-available --volume-ids $VOLUME_ID
Attach to Helper
HELPER_ID=i-helper123
aws ec2 attach-volume --volume-id $VOLUME_ID --instance-id $HELPER_ID --device /dev/xvdf
Inject Key
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
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
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.