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:
- Stop the EC2 instance & detach its
/dev/xvda1volume — see Detaching an Amazon EBS volume from a Linux instance. Let’s call this instance N & volume V.
- 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.
- Attach volume V to instance S as
- SSH into instance S & mount volume V —
sudo mount /dev/xvdf1 /mnt/tmp.
/mnt/tmp/home/ubuntu/.ssh/authorized_keys. Depending on the instance’s AMI, this path will be one of
- Logout & terminate instance S.
- Reattach volume V to instance N as
- 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!
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
- Amazon EC2 key pairs and Linux instances
- Uploading Personal ssh Keys to Amazon EC2
- Transitioning your pem/key on an EC2 instance
- Change ssh key-pair of Running EC2 Instance
- Fixing Files on the Root EBS Volume of an EC2 Instance
- How can I connect to my Amazon EC2 instance if I lost my SSH key pair after its initial launch?