ℹ️ 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 key
ssh-rsa AAAAB3NzaC... Hjxu7JiYNoasuv1SH3Dwf0PD 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).
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 AAAAB3NzaC1yc2EAAAADAQ... Hjxu7JiYNoasuv1SH3Dwf0PD new key
ec2-user
with the appropriate username for your Linux distribution if different⚠️ Warning: The username varies by Linux distribution. Common examples include:
ec2-user
ubuntu
ec2-user
or root
admin
ec2-user
or root
Start 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.