I want to use user data to replace a lost SSH key pair in an already launched Amazon Elastic Compute Cloud (Amazon EC2) instance. How can I do that?
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. Open the Amazon EC2 console.
4. Choose Actions, Instance Settings, and then choose View/Change User Data.
5. 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:
- ssh-rsa keypair
Replace username with your username, such as ec2-user, and replace keypair with the public key generated in step 1.
6. For the users-groups parameter, specify once.
7. Choose Save.
8. Start your Amazon EC2 instance again.
9. After the cloud-init phase is complete, validate that the public key has been replaced.
Important: For security reasons, remove the script from the User Data field, because the script contains a key pair.
Did this page help you? Yes | No
Back to the AWS Support Knowledge Center
Need help? Visit the AWS Support Center
Published: 2019-02-12