How to Recover EC2 Access After Losing Your .pem Key


Step 1: Create a New Key Pair
Go to EC2 Dashboard → Key Pairs
Click Create Key Pair
Download and store the new
.pem
file safely
Step 2: Stop the Affected Instance
Go to Instances
Stop the EC2 instance you can’t access
You can’t modify volumes on a running instance.
Step 3: Detach the Root Volume
Go to Elastic Block Store → Volumes
Find the root volume attached to the stopped instance
Detach it
Step 4: Launch a Temporary EC2 Instance
Launch a new temporary instance (any Linux AMI)
Use your new key pair while launching
Step 5: Attach the Root Volume to Temporary Instance
Attach the previously detached volume to the temporary instance
Set it as a secondary device (e.g.,
/dev/xvdf
)
Step 6: Replace the Authorized Key
SSH into the temporary instance:
ssh -i new-key.pem ec2-user@<temp-instance-public-ip>
Mount the attached volume:
sudo mkdir /mnt/recovery
sudo mount /dev/xvdf1 /mnt/recovery
Replace the old SSH key:
sudo nano /mnt/recovery/home/ec2-user/.ssh/authorized_keys
- Paste the public key from your new key pair
Save and exit.
Step 7: Detach and Re-Attach the Volume
Unmount the volume:
sudo umount /mnt/recovery
Detach it from the temporary instance
Attach it back to the original instance as the root volume
Step 8: Start the Original Instance
Now start your original EC2 instance. You should be able to SSH using your new .pem
file.
Subscribe to my newsletter
Read articles from Durkesh blogs directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
