1. First, we have to create a new key pair.
2. If we create the private key in the Amazon EC2 console, we have to retrieve the public key for the key pair.
3. Now, Open the Amazon EC2 console.
4. And Stop our instance.
5. Now, we have to Choose Actions, Instance Settings, and then choose Edit user data.
6. Then, we have to copy the following script into the Edit user data dialogue 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
------------------------------------------------------------
Now replace the username with our user name, such as ec2-user. We can enter the default user name or enter a custom user name.
Replace Public Keypair with the public key we had retrieved in step 2. And make sure to enter the full public key, starting with ssh-rsa.
7. Now, Choose Save.
8. Then, we will start our instance.
9. And after the cloud-init phase is completed, validate that the public key was replaced.
*Important: As the above script contains a key pair, remove the script from the User Data field.
10. Now, we will stop our instance.
11. Then, Choose Actions, Instance Settings, and then we choose Edit user data.
12. Now, we have to delete all the text in the Edit user data dialogue box, and then we will choose Save.
13. Finally, we will start our instance.
If that instance is a managed instance in the AWS Systems Manager, we will use the AWSSupport-ResetAccess document to recover our lost key pair. AWS Support Reset Access automatically generates and adds a new key pair using the EC2 Rescue for Linux tool on the specified EC2 instance.
Our instance’s new SSH private key is encrypted now and saved in the AWS Systems Manager Parameter Store. The parameter name is /ec2rl/OpenSSH/instance_id/key. Now we create a new .pem file with this parameter's value as its content, and we use it to connect back to our unreachable instance.
Note: The Automation workflow creates a backup file, password-enabled Amazon Machine Image (AMI). The new Amazon Image(AMI) is not automatically deleted and remains in our account.
To locate these AMIs: