Importing SSH keys on AWS

08/05/2011 07:22 pm

Here's a quick tip for managing AWS keys a little differently—

All the tutorials you'll find refer to downloading the generated private key from the AWS console. This is fine for the first 10 times you create instances or cloud setups, but the time will come when you want to use the same key for lots of instances or you want to use your own keys all the time.

AWS has an "import keypair" method than can be reached easily using the AWS CLI tools. This command takes a public key and uploads it to your AWS account so that instances can be launched with it.

If you haven't already installed the AWS CLI tools, grab them from the Amazon EC2 API Tools website and put them in /usr/local/ec2-api-tools/. Add the environment variables:

export EC2_HOME=/path/to/ec2-tools/
export PATH=$PATH:$EC2_HOME/bin
export EC2_PRIVATE_KEY=`ls -C $EC2_HOME/pk-*.pem`
export EC2_CERT=`ls -C $EC2_HOME/cert-*.pem`

With this installed, you have access to loads of the API that isn't always exposed via GUIs – a nice chance to get under the hood.

Start by generating an ssh key-pair in the usual way:


And follow the instructions. This generates two files: the public key, id_rsa, and the private key,

It's the public key that you need to upload, using the ec2-import-keypair command:

ec2-import-keypair dan-key --public-key-file ~/.ssh/

Using the ec2-describe-keypairs command, you can see the newly uploaded keypair:

  KEYPAIR dan-key
  KEYPAIR my-key
  KEYPAIR your-key

Instances can now be launched using the key by firing off the ec2-run-instances command:

ec2-run-instances ami-abc123ab -k dan-key

Finally, if you want to generate keys on the fly, the CLI tools can help you do this with the ec2-add-keypair command. This works in reverse to the ec2-import-keypair command by generating the key on AWS and passing the private key back to you:

ec2-add-keypair my-new-key
  KEYPAIR dangen1





So, when would you import a key rather than generate one? If you have limited permissions on your local machine or if you want to create instances from a known set of keys, uploading the key makes more sense.

If you have a strong internal security policy and need to keep keys in rotation, uploading the public keys will be better than having any number of keys generated on AWS.

You can find out more about this command at the AWS CLI docs:

Related content

Dan Frost is Technical Director of, cloud hosting consultants and web developers based in London and Brighton, UK

Dan has been building cloud hosting, writing, and talking about the cloud since before it was trendy. Since he spun up his first AWS instance, he's been trying out new services and finding ways of getting more out of hardware without actually owning any of it.

Mon Tue Wed Thu Fri Sat Sun
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31