Recover or Change Lost Key Pair EC2 Instance
What the …(i know your feeling)… my key pair was lost?
sometime you don’t realize that your key pair for connecting to your EC2 Instance was lost or you have old EC2 instance since 5 years old. How to solve this? you can use user data.
Pre-requisites:
- Server without/lost key.
- Server for recover that still have key pair.
Step by step:
- Stop the server was lost the key pair
2. Update the user data for the server was lost server key
Fill the user data with this 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:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
/bin/echo -e "your-ssh-key" >> /home/ec2-user/.ssh/authorized_keys
--//
Very recomended to copy the script in notepad and disable the word wrap (so it just one line) :
Copy the ssh-key from recover server
3. Start again the server was lost key pair, and connect to the server using the key-pair from recover server. Copy the public IP address of server was lost key and access via SSH.
4. Boom, you now can connect to your lovely EC2 Instance
Thanks, I hope this usefull for you!
source: https://aws.amazon.com/id/premiumsupport/knowledge-center/execute-user-data-ec2/