Most of the AWS documentation about ssh keys focuses on creating them within AWS and passing the .pem files to ssh with -i. However, you can also generate an ssh key pair on your computer and import it into AWS.  The advantages of this is that you do not have to generate a different pem file for each region.  In fact, you do not have to deal with pem files at all. 

You may already have an ssh key pair that you'd like to use.  If not, you can generate one with this command (I think it works on linux as well as Mac OSX) - give the key whatever name you want (e.g. aws_rsa) and, if you wish, a password (optional):

ssh-keygen -t rsa

To log in to AWS EC2 instances, you have to give AWS the public component of this key pair.  You can do this by going to your AWS EC2 Dashboard for a particular region and selecting Key Pairs from the Resource Summary at the top or the Network and Security menu on the left.  Then select Import Key Pair.  This will bring up a dialog box that asks you for the public key.

You can either import the public key file (~/.ssh/aws_rsa.pub in this example) or you can run the following command (type aws_rsa when it asks you to specify the key) to print the public key to the screen:

ssh-keygen -y

Then copy and paste this into the AWS dialog box where it asks for the public key.   Note that you have to repeat this Import Key Pair process for each region you intend to use.  However, you can use the same key for all regions.

Then you are set.   The next step is to start your ssh agent in one or more windows on your computer and activate the key pair - for example:

ssh-agent bash
ssh-add ~/.ssh/aws_rsa

You only have to do this once.  Now whenever you launch an EC2 instance in any region (provided you imported the key pair into that region), you can log into it normally using just the instance's public IP address (IPv4) and the appropriate user name (ec2-user for the Amazon Linux 2 AMI).  For example:

ssh ec2-user@34.216.76.135

And, similarly, you can transfer files using scp.  Very convenient.  Let me (Mark) know if you have any questions/issues.



  • No labels