For various security reasons it can be a good idea to change ssh keys. Amazon doesn’t actually let you change keys for a live instance. If you can easily restart your instance, that’s the best way to change the key pair. However, sometimes restarting an instance can be a much larger hassle than manually changing the keys. We recently ran into this very situation, so here’s a workaround:
- Generate a new key pair from your AWS account
- Generate a public key from the private key AWS generates
- Add the key to the instance’s authorized_keys
- Remove the old public key from authorized_keys
- Make sure you change the key pair on AWS next time the instance is restarted!
Generate a new key pair
Login to your AWS management console. Go the ec2 tab, then select “key pairs” from the sidebar. Now all you have to do is click “Create key pair.” AWS will give you the private key and store the public key. Copy the private key into a file on your local computer. We’ll call it my_key.pem for this walkthrough.
Generate a public key
Now that you have my_key.pem, we need to generate a public key to upload to the instance. Amazon has a public key stored my_key.pem, but we don’t have access to it so we need to generate a new one. First, change the permissions on my_key.pem by running ‘chmod 0600 my_key.pem. Then run ‘ssh-keygen -y’, you will then be prompted for the private key file, so enter the path to my_key.pem. You’ll then get an output on your console of the public key. You can save this in my_key.pub.
OS X NOTE: Macs can add metadata attributes to files. You need to remove these attributes before ssh will generate a public key. In the directory containing my_key.pem, run ‘ls -l@’ to see if there are any attributes connected. If there are, run xattr -d “[attribute name]”.
Add the public key to your instance
Now ssh into your instance using your old key and navigate to ~/.ssh. The directory contains an ‘authorized_keys’ file. You need to append my_key.pub to this file. I just copy and pasted the key using nano. Make sure you save the authorized_keys file.
Remove the old key
In the same authorized_keys file, remove the old key. Unless you added your own keys, the file will only contain your new public key and the old public key. Simply delete the old public key and save authorized_keys.
At this point, you’re done! Now you can ssh in with your new key: ssh -i /path/to/my_key.pem root@ec2address. However, next time you restart the instance, you will lose your key changes unless you specify the new key you generated on AWS.