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:

1.    Create a new key pair.

2.    Open the Amazon EC2 console.

3.    Stop your instance.

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"

- [users-groups, once]
  - name: username
    - 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