How to recover and access AWS EC2 instances if we lost pem file?

Satish Mali
2 min readOct 7, 2022

I want to connect to my Amazon EC2 instance but have lost the SSH key pair. How can I connect to the instance?

Important: This method require a stop and start of the instance.

Step 1. Create a new key pair (From ec2 dashboard inside Network & security).

Create new key pair

Step 2. Retrieve the public key for the key pair from private key (Do in local system that will used in step 6).

Retrieve public key using command in Linux.

Step 3. Open the Amazon EC2 console.

Step 4. Stop your instance.

Step 5. Choose Actions, Instance settings, Edit user data.

Click on Edit user data
Instance settings -> Edit user Data

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

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

User data as text

Step 7. Choose save.

Step 8. Start your instance.

Step 9. Login with new pem file. now you able to login with new pem file.

Step 10. Now again stop instance.

Step 11. Clear script from Edit user data dialog box. because each time we restart instance it will execute every time.

Step 12. Again start EC2 instance.

✌!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Satish Mali
Satish Mali

No responses yet

Write a response