DEV Community

Aye Nyein San
Aye Nyein San

Posted on

How to Replace Lost KeyPair to EC2 Instance

Sometimes, we accidentally happen to misplace or lost our important key pair of EC2 instances.
At this time, we couldn't access our server for development . When this happen, things come to stuck ...!
In this blog , I'll show you a simple way to regain access your server (EC2 instance) with newly created key pair as replacement.

I am unable to access my EC2 instance, named 'lost_KeyPair_EC2', because I have lost the corresponding key pair file.
Image description

In the lost_KeyPair_EC2, there is file called initialVM.txt.
Image description

First, we need to create a new key pair since we lost our old ones.
Go to EC2 => KeyPairs=> Create Key pair

Create Key pair

I created key pair with .pem with the name (replacement_key). You can give any name.

Keypair

Since we cannot access the current EC2 instance, we can create the current instance template with Amazon Machine Image(AMI) attaching with the new key pair.

An Amazon Machine Image (AMI) serves as a template for launching EC2 instances. It is region-specific, meaning that if your EC2 instance is located in us-east-1c, the corresponding AMI must also be available within the us-east-1 region.

Select the instance > Click Actions > choose Image and templates > select Create image

EC2Image

AMIs
You can check created AMI in the EC2 > AMIs

Image description

Select the AMI and launch instance from the template.
When you create EC2 instance , don't forget to select your newly created key pair.
AMIs

Once the new instance is running, you can access it using the newly created key pair:
ssh -i replacement_key.pem ubuntu@<your-ec2-instance-ip>

If everything was done correctly, you should see the same data as in the original instance.

For example, inside my replacement EC2 instance, I can see the initialVM.txt file from the lost instance.
Replacement_VM

Now, you can use your replacement instance with the new key pair, even though the original key pair file was lost.

Losing an EC2 key pair doesn't mean losing access to your instance permanently. By creating a new key pair, using an AMI to launch a replacement instance, and attaching the new key pair, you can regain access safely and efficiently.

That's it! πŸŽ‰
Happy coding! πŸš€

Top comments (0)