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:

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.

4.    Stop your instance.

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:

1.    Stop your instance.

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.