ℹ️ Information: The key pair is essential for authenticating SSH connections to your Amazon EC2 Linux instances. If you lose your private key file, you can use EC2 user data to inject a new SSH key, allowing you to regain access without rebuilding your instance.
⚠️ Warning: This recovery process requires stopping your EC2 instance. If your instance uses instance store volumes, stopping it will result in data loss. Ensure you have backed up any critical data before proceeding.
Navigate to the EC2 console:

Generate a new key pair:

Configure the key pair settings:
new-key
💡 Pro Tip: The private key file (new-key.pem) will be automatically downloaded to your local machine. Store this file securely as it cannot be recovered if lost.
Open PuTTYgen:

Retrieve the public key:
new keyssh-rsa AAAAB3NzaC1yc2EAAAADAQA......+xZy/pOTTV new key
🔒 Security Note: The public key is safe to share, but never share your private key (.pem file). The private key should be stored securely and with appropriate permissions (chmod 400 on Linux/macOS). 3. Save the private key in .ppk format:
In PuTTYgen, click Save private key
When prompted, choose Yes to save without a passphrase (if applicable)
Enter the file name as new-key and Save the file
This .ppk file will be required when connecting to the instance using PuTTY.

Stop the EC2 instance:

Access the user data settings:

Configure the cloud-init script:
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 AAAAB3NzaC1yc2EAAAADAQA......+xZy/pOTTV new key
ec2-user with the appropriate username for your Linux distribution if different
⚠️ Warning: The username varies by Linux distribution. Common examples include, refer to: Connect to your Linux instance using SSH, General connection prerequisites
ec2-userubuntuec2-user or rootadminec2-user or rootStart the EC2 instance:

Wait for initialization:
Prepare for connection:

Configure PuTTY:

Establish the connection:

💡 Pro Tip: You can verify the key was properly added by checking the ~/.ssh/authorized_keys file on your instance. Each line in this file represents an authorized public key.
🔒 Security Note: The cloud-init process only runs once when the instance starts. If you make a mistake in your user data configuration, you’ll need to stop and start the instance again to trigger another run.
ℹ️ Information: This method works because cloud-init processes user data during instance initialization, allowing you to inject configuration changes like SSH keys without needing to access the instance first.