Have you lost your AWS EC2 Instance SSH key pair…

Siva Naik
3 min readAug 5, 2022

Hola 👋🏻,

Don’t worry you can connect with your instance.

Lets’s understand the scenario When you create an SSH KeyPair. The Public key is configured in your EC2 Instance and the private key will be downloaded into your Local Operating system.

  • We use the private key to connect with EC2 Instance which is the pair of public keys configured in Instance.
  • In any way, if we can change the public key in Instance with another public key, we can connect with the private key of the respective key.

Keys

  • Public Key (Configuerd in EC2 Instance)
  • Private Key (Used to connect with EC2 Instance)
  1. Create new key pair

Add the above Configuration and Create Key Pair. You will get a prompt to save the private key in your local Operating System.

2. Stop Instance

Select the EC2 Instance and stop the instance from Instance State.

Note: You will lose your Public IP and Ephemeral Data on Instance.

3. Edit User Data

3.1 Generate Public Key from downloaded Private Key.

we can generate the Public key from the Private key which we downloaded using the ssh-keygen command

ssh-keygen -y -f /path_to_key_pair/my-key-pair.pem

The above command will generate the public key. Copy the Public Key from ssh-rsa to end.

3.2 Edit the user data

User data is the script that is executed in the boot process to do configuration. we can configure the public key we got in the previous step in user data.

Select the Instance, Actions -> Instance settings -> Edit user data

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [users-groups, once]
users:
- name: username
ssh-authorized-keys:
- PublicKeypair
  • Replace the username and PublicKeypair (which is in bold). The username is that you use to connect with the instance and PublicKeypair. Is that key that you copied from above part
  • Save the configuration

4. Start Instance

Select the Instance -> Instance State -> Start Instance

5. Connect with Instance

5. 1 change the key file type

chmod  400  /path_to_key_pair/my-key-pair.pem

5.2 Connect with Instance

ssh -i "recover.pem" ec2-user@ec2-*-66-98-198.ap-south-1.compute.amazonaws.com

Finally! We made it. 🥳

Further Reading.

You can DM me on LinkedIn. If you face any difficulty in the process.

Here is my LinkedIn Profile https://www.linkedin.com/in/sivanaik/

--

--

Siva Naik
Siva Naik

Written by Siva Naik

Opensource Contributor | DevOps Engineer

Responses (1)