Mon Nov 25 2024

Change Your EC2 Instance Key Pair Without SSH Access

We’ve all been there: losing access to an EC2 instance because a key pair went astray can be frustrating. If you’ve lost your private key and need to regain SSH access, you can swap out the old key pair for a new one. This guide will walk you through the process using the AWS Management Console.

You’ll need to employ a stop-and-swap method, essentially enlisting the help of a temporary EC2 instance to modify the original instance’s key pair. Let’s dive right in.

Steps to Change Your EC2 Key Pair

  1. Stop the EC2 Instance: Begin by stopping the EC2 instance for which you’ve lost the SSH key. This will enable safe modification of the instance’s resources. Navigate to the EC2 dashboard in the AWS Management Console and stop the instance.

  2. Detach the Root Volume: Identify and detach the instance’s root volume (let’s call it Volume A). This is generally attached as /dev/xvda1. In the EC2 dashboard, select the instance, find attached volumes, and detach the root volume, ensuring it’s no longer linked to any instance. AWS Documentation on Detaching EBS Volumes.

  3. Launch a Temporary Instance: Create a new, minimal EC2 instance using an instance type like t4g.micro, to keep costs low. Make sure it’s launched in the same subnet as the original instance to prevent network configuration issues. Use the new key pair for this instance.

  4. Attach and Mount Volume A: Attach Volume A to the new (temporary) instance as an additional volume (e.g., /dev/xvdf). After attaching, connect to the temporary instance via SSH.

    $ sudo mkdir /mnt/tmp
    $ sudo mount /dev/xvdf1 /mnt/tmp
    
  5. Update the Authorized Keys File: In your temporary instance, you’ll need to replace the existing authorized_keys file. Copy your new key into the file located in the mounted directory.

    $ cp ~/.ssh/authorized_keys /mnt/tmp/home/ubuntu/.ssh/authorized_keys
    
  6. Cleanup: After modifying the authorized_keys file, logout from the temporary instance.

  7. Terminate the Temporary Instance: To avoid incurring unnecessary charges, terminate the temporary EC2 instance once you’ve completed the key update tasks.

  8. Reattach Volume A to the Original Instance: Reattach Volume A to the original instance as /dev/xvda.

  9. Restart the Main Instance: With everything set up, you can now start your original EC2 instance again. Use the new private key file (.pem) to access the instance over SSH.

Note: If you’re unfamiliar with attaching and detaching volumes or connecting to instances via SSH, refer to the AWS EC2 User Guide.

By following these steps meticulously, you regain access to your EC2 instance without losing any data or configurations. Remember to safely store your private keys to prevent similar issues in the future.