How to recover access to the EC2 instance for which the key pair lost

If ssh key pair lost, its not possible to connect to EC2 instances. But there is a method to get the access back and this article explains those steps in detail.

Step1: Login to AWS console.

Step2: Select the EC2 management page.

Step3: From the left menu, choose Key Pairs under Network & Security.

Step4: Select Create key pair and proceed.

Step5: Download new key pair.

Step6: Retrieve the public key from the key pair by following the steps mentioned in below url.

Step7: Select the required instance from list of instances in EC2 management page.

Step8: Stop the selected instance.

Step9: Choose Instance settings under Actions and Edit user data for the selected instance.

Step10: Copy the following script into the Edit user data dialog box.

#cloud-config
ssh_deletekeys: false
ssh_authorized_keys:
    - PUBLICKEY
cloud_final_modules:
    - [ssh, always]

Here we need to replace PUBLICKEY with the public key starting with ssh-rsa retrieved earlier.

Step11: Start the instance.

Step12: Verify that instance is accessible using the new key.

Step13: Stop the instance again.

Step14: Choose Instance settings under Actions and Edit user data for the selected instance.

Step15: Delete all texts in the Edit user data dialog box and Save.

Step16: Start the instance.

That's all…