Change Key Pair of an EC2 Instance
Once an EC2 instance is running you cannot change the key pair at the metadata level, but you can update authorized_keys to accept a new SSH public key. Three methods are below.
Method 1 – Update authorized_keys via a temporary instance (EBS)
- Stop the target EC2 instance.
- Detach its root volume (
/dev/sda1) — call it Volume A. - Launch a temporary
t3.microin the same subnet using the new key pair. - Attach Volume A to the temp instance as
/dev/xvdf. - SSH in and mount it:
sudo mount /dev/xvdf1 /mnt/tmp - Copy the new public key:
sudo cp ~/.ssh/authorized_keys /mnt/tmp/home/ubuntu/.ssh/authorized_keys
(replaceubuntuwithec2-userorrootas needed) - Unmount:
sudo umount /mnt/tmp - Detach Volume A, re-attach to the original instance as
/dev/sda1, start it. - Terminate the temporary instance.
Method 2 – Add new public key while you still have access
ssh-keygen -f YOURKEY.pem -y >> ~/.ssh/authorized_keys
Always verify the new key works in a separate terminal before closing the current session.
authorized_keys locations by AMI
- Amazon Linux / RHEL:
/home/ec2-user/.ssh/authorized_keys - Ubuntu:
/home/ubuntu/.ssh/authorized_keys - Root:
/root/.ssh/authorized_keys
Method 3 – Save as AMI and relaunch (EBS-backed only)
- Create an AMI from the instance (Actions → Image and templates → Create image).
- Launch a new instance from that AMI, selecting the new key pair.
- Move any Elastic IP to the new instance, terminate the old one.