How to Change the SSH Key Pair for an AWS EC2 Instance?

There are several reasons for needing to change (or add) the SSH key pair for your existing EC2 instances. Maybe you lost the private key or you just want to add more keys to the instance so users with those keys can login to it. Let’s see how this can be done.

If you lost access to the instance…

If you’ve misplaced your private key & hence are unable to SSH into your instance, follow these steps to restore access to the instance:

  1. Stop the EC2 instance & detach its /dev/xvda1 volume — see Detaching an Amazon EBS volume from a Linux instance. Let’s call this instance N & volume V.
  2. Launch a new instance in the same subnet as instance N with the key pair you want to use with instance N. Let’s call this instance S.
  3. Attach volume V to instance S as /dev/xvdf (or /dev/sdf).
  4. SSH into instance S & mount volume V — sudo mount /dev/xvdf1 /mnt/tmp.
  5. Copy ~/.ssh/authorized_keys to /mnt/tmp/home/ubuntu/.ssh/authorized_keys. Depending on the instance’s AMI, this path will be one of /home/ec2-user/.ssh/authorized_keys, /home/ubuntu/.ssh/authorized_keys or /root/.ssh/authorized_keys.
  6. Logout & terminate instance S.
  7. Reattach volume V to instance N as /dev/xvda (or /dev/sda1).
  8. Start instance N & SSH into it using the key pair used for instance S.

NOTE — The AWS EC2 console will still show the name of the old key pair, but your new key pair will work.

If you have access to the instance…

All you need to do in this case is to SSH into the instance using your old key & add the public key of your new key pair to the ~/.ssh/authorized_keys file. You can then SSH into the instance using your new key as well!

Other ways…

You could also:

  • Select the instance in the console, select “Launch more like this” from the Actions menu & provide your new key pair. NOTE — This will create a new instance.
  • Create an AMI of the instance & launch a new instance from the AMI providing your new key pair.
  • If your instance has the Systems Manager agent installed, go to Systems Manager > Automation > Execute Automation > AWSSupport-TroubleshootSSH. See Walkthrough: Reset passwords and SSH keys on EC2 instances.
  • Add the following to the instance user data. Then stop & start the instance:
# cloud-config
bootcmd:
- echo 'ssh-rsa AAA...' > /root/.ssh/authorized_keys

References