The key pair is essential for encrypting and decrypting credentials for the EC2 virtual server. In the event of a lost key pair, follow these steps to create a new key pair and continue SSH access to EC2.
Note: This solution involves stopping the EC2 instance. If the instance uses instance store volumes, stopping it may result in data loss. Ensure data backup before proceeding.
Create a New Key Pair
Retrieve the Public Key
ssh-rsa AAAAB3NzaC... Hjxu7JiYNoasuv1SH3Dwf0PD new key
Update EC2 User Data
Stop the EC2 instance when its status is Stopped.
Go to Actions > Instance settings > Edit user data.
Choose Modify user data as text.
Enter the EC2 user name (e.g., ec2-user
) under the line name.
Paste the copied Public key value under the line ssh-authorized-keys.
Copy and paste the following statements:
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: ec2-user
ssh-authorized-keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQ... Hjxu7JiYNoasuv1SH3Dwf0PD new key
Save the user data.
Start the EC2 Instance
Access EC2 Linux-instance
Congratulations! You have successfully accessed the EC2 Linux instance by replacing the public key.
Important Notes: