If you need to connect to an Amazon EC2 instance without an original SSH key pair on a new device, you can follow these steps:
- Create a new key pair or use existing key.
- If you create a private key in the Amazon EC2 console, retrieve the public key of the key pair.
- Open the Amazon EC2 console.
- Stop the instance.
- Choose Actions, Instance Settings > Edit User Data.
- Copy the following script into the Edit 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 xxxxxxxxxxx (your public key)
Replace username
with your username, such as ec2-user. You can enter the default username or a custom username (if previously set for the instance). For a list of default usernames, see Getting Instance-Related Information.
Replace PublicKeypair
with the public key retrieved in step 2. Make sure to enter the entire public key, starting with ssh-rsa
.
- Choose Save.
- Start your instance.
- After the cloud-init phase is complete, confirm that the public key has been replaced.
Important: Since the script contains a key pair, remove the script from the user data field.
- Stop the instance.
- Choose Actions, Instance Settings, Edit User Data.
- Delete all text in the Edit User Data dialog box, then choose Save.
- Start your instance.