Uploading Personal ssh Keys to Amazon EC2

Amazon recently launched the ability to upload your own ssh public key to EC2 so that it can be passed to new instances when they are launched. Prior to this you always had to use an ssh keypair that was generated by Amazon.

The benefits of using your own ssh key include:

  • Amazon never sees the private part of the ssh key (though they promise they do not save a copy after you downloaded it and we all trust them with this)

  • The private part of the ssh key is never transmitted over the network (though it always goes over an encrypted connection and we mostly trust this)

  • You can now upload the same public ssh key to all EC2 regions, so you no longer have to keep track of a separate ssh key for each region.

  • You can use your default personal ssh key with brand new EC2 instances, so you no longer have to remember to specify options like -i EC2KEYPAIR in every ssh, scp, rsync command.

If you haven’t yet created an ssh key for your local system, it can be done with the command:

ssh-keygen

You can accept the default file locations, and I recommend using a secure passphrase to keep the key safe.

Here are some sample commands that will upload to all existing regions your personal ssh public key from the default file location on Ubuntu, giving it an EC2 keypair name of your current username. Adjust to suit your preferences:

keypair=$USER  # or some name that is meaningful to youpublickeyfile=$HOME/.ssh/id_rsa.pubregions=$(ec2-describe-regions | cut -f2)for region in $regions; do  echo $region  ec2-import-keypair --region $region --public-key-file $publickeyfile $keypairdone

When you start new instances, you can now specify this new keypair name and EC2 will provide the previously uploaded public ssh key to the instance, allowing you to ssh in. For example:

ec2-run-instances --key $USER ami-508c7839[...]ec2-describe-instances i-88eb15e5[...]ssh ubuntu@ec2-184-73-107-172.compute-1.amazonaws.com

Don’t forget to terminate the instance if you started one to test this.

[Update]

Based on a Twitter question, I tested uploading a DSA public ssh key (instead of RSA) and got this error from Amazon:

Client.InvalidKeyPair.Format: Invalid DER encoded key material

I don’t see why DSA would not work since it’s just a blurb of text being stored by EC2 and passed to the instance to add to $HOME/.ssh/authorized_keys but there you have it.

 

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s