How can I use user data to replace a lost SSH key pair after the initial launch of my Amazon EC2 instance?
Last updated: 2019-12-10
I want to use user data to replace a lost SSH key pair in an Amazon Elastic Compute Cloud (Amazon EC2) instance that's already launched. How can I do that?
Resolution
Warning: Before starting this procedure, be aware of the following:
- Stopping and restarting the instance erases any data on instance store volumes. Be sure that you back up any data on the instance store volume that you want to keep.
- Stopping and restarting the instance changes the public IP address of your instance. It's a best practice to use an Elastic IP address instead of a public IP address when routing external traffic to your instance.
1. Create a new key pair.
2. If you create the private key in the Amazon EC2 console, retrieve the public key for the key pair.
3. Open the Amazon EC2 console.
5. Choose Actions, Instance Settings, and then choose View/Change User Data.
6. Copy the following script into the View/Change User Data dialog 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
Replace username with your user name, such as ec2-user. You can enter the default user name, or enter a custom user name, if one was previously set up for the instance. For a list of default user names, see General Prerequisites for Connecting to Your Instance.
Replace PublicKeypair with the public key retrieved in step 2. Make sure that you enter all of the public key as is, starting with ssh-rsa.
7. Select Save.
8. Start your Amazon EC2 instance.
9. After the cloud-init phase is complete, validate that the public key was replaced.
Important: Because the script contains a key pair, remove the script from the User Data field for security best practices. To remove the script:
2. Choose Actions, Instance Settings, and then choose View/Change User Data.
3. Delete all the text in the View/Change User Data dialog box, and then select Save.
4. Start your Amazon EC2 instance.
Note: If your instance is Amazon Linux 2 2.0.20190618 or later, you can use EC2 Instance Connect to connect to the instance.
Related Information
Did this article help you?
Anything we could improve?
Need more help?