Can't change assigned key pair on amazon ec2 instance

Solution 1:

When you specify a keypair on running an instance, most public AMIs will copy the public ssh key for that keypair into a .ssh/authorized_keys file in the primary user account's home directory. This is only done on first boot.

The user account varies depending on the Linux distro and the AMI publisher. Some common user accounts include root, ec2-user, and ubuntu, so the default file might be one of:

/root/.ssh/authorized_keys
/home/ec2-user/.ssh/authorized_keys
/home/ubuntu/.ssh/authorized_keys

Note: The above described behavior is not enforced by EC2, but is simply a de facto standard implemented by most popular public AMIs.

If you want to prevent the initial keypair from having access to a running instance, simply edit the .ssh/authorized_keys file, remove that public ssh key entry, and add the public ssh key you want to have access.

This is standard ssh key management, not specific to EC2. This is the key to your server's security so it is important to understand what you are doing. Read up on ssh to make sure you do this safely.

Warning! Make sure you test ssh with the new key in a separate terminal before you terminate your existing ssh session that was used to edit the file! If you break the authorized_keys file you risk not being able to connect to the instance.

Make sure you add the public ssh key to the authorized_keys file, not the private ssh key! If you saved your private ssh key to, say, KEYPAIR.pem, then here's a command that will output the corresponding public key:

ssh-keygen -y -f KEYPAIR.pem

If the above seems too complicated to you, then it is fine to start a new instance with a new keypair specified. You should always have a procedure in place to be able to start replacement instances anyway as your existing instance could fail at any time.

In a related topic, I recommend using your own ssh keys instead of having Amazon generate keypairs for you. It makes things easier all around. Here's an article I wrote on the topic:

Uploading Personal ssh Keys to Amazon EC2
http://alestic.com/2010/10/ec2-ssh-keys

Solution 2:

I don't believe there is a way to assign a new key-pair to an instance, but you could create an AMI image from the current instance, then create an instance of the new AMI, assigning it the new key-pair upon creation. Once the new instance is up and running, just stop/terminate the old instance.

The new instance will have a different IP address to the old instance. If that's a problem, you may want to assign an elastic IP to the old instance, then, when you're ready, re-assign the elastic IP to the new instance.

It is my understanding that Amazon only inserts your key-pair's public key into an instance upon creation of a new instance.

Solution 3:

Second option is to replace a lost key pair on an EC2 instance as long as it's an EBS backed instance. The following link may help:

replace-lost-keypair