How to Recover EC2 Access After Losing Your .pem Key

Durkesh blogsDurkesh blogs
2 min read

Step 1: Create a New Key Pair

  1. Go to EC2 Dashboard → Key Pairs

  2. Click Create Key Pair

  3. Download and store the new .pem file safely

Step 2: Stop the Affected Instance

  1. Go to Instances

  2. Stop the EC2 instance you can’t access

You can’t modify volumes on a running instance.

Step 3: Detach the Root Volume

  1. Go to Elastic Block Store → Volumes

  2. Find the root volume attached to the stopped instance

  3. Detach it

Step 4: Launch a Temporary EC2 Instance

  1. Launch a new temporary instance (any Linux AMI)

  2. Use your new key pair while launching

Step 5: Attach the Root Volume to Temporary Instance

  1. Attach the previously detached volume to the temporary instance

  2. 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

  1. Unmount the volume:

     sudo umount /mnt/recovery
    
  2. Detach it from the temporary instance

  3. 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.

0
Subscribe to my newsletter

Read articles from Durkesh blogs directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Durkesh blogs
Durkesh blogs