A key pair is just an SSH key pair that we have registered with AWS, and it is necessary to have them even when running Microsoft Windows instances.
There are two ways to create a key pair: We can import an SSH public key we’ve already created or Amazon can generate the key pair and send us the private key.
You generate the key
Creating our own keys and importing them has some advantages: being able to use a passphrase if we want; only the public key moves over the network, as opposed to the private one when Amazon creates it; using the command line tools it is easier because no copying and pasting or file editing is needed.
The following command will create an SSH key, using RSA encryption, with a comment of “key-name”, and save it in the .ssh directory of our home directory, with the private key file key-name, and public key file key-name.pub
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): Your optional passphrase here
Enter same passphrase again: Your optional passphrase here
Your identification has been saved in /home/user/.ssh/key-name.
Your public key has been saved in /home/user/.ssh/key-name.pub.
The key fingerprint is:
a4:1c:47:0c:1b:09:6d:18:ee:4a:33:94:9b:db:17:7b key-name
The key's randomart image is:
+--[ RSA 2048]----+
| o=o+. |
| o. ++. |
| o ..o o |
| . + . = |
| * . + S |
| . * o |
| o . o E |
| . . |
| |
+-----------------+
Now that we have the SSH key pair, we can import to EC2
Example API Request
1
2
3
4
5
https://ec2.us-east-1.amazonaws.com/
?Action=ImportKeyPair
&KeyName=key-name
&PublicKeyMaterial=`openssl enc -base64 -A -in ~/.ssh/key-name.pub`
&*AUTHPARAMS*
Warning Do not use a key pair with a passphrase to start a Microsoft Windows instance, the password cannot be decrypted then.
Amazon originally had the command in the ec2-api-tools that did this named ec2-add-keypair, however later versions added ec2-create-keypair, which is the one they currently have documented
We will have to copy from -----BEGIN RSA PRIVATE KEY----- through -----END RSA PRIVATE KEY-----, and put it into a file. The name of the file is not important, so long as we remember which key pair it is associated with. For this article, let us put it in ~/.ssh/example.pem. We also need to remember to include -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- in the file.
The easier alternative is to delete the first line and direct the rest of the output into a file, like so:
Console - user@hostname ~ $
1
2
3
ec2-add-keypair \
--region us-east-1 \
example | sed 1d > ~/.ssh/example.pem