How can I use a single SSH key pair for all my AWS Regions?

Last updated: 2020-02-17

I want to use the same SSH key pair to access my Amazon Elastic Compute Cloud (Amazon EC2) instances in all my AWS Regions. How do I do that?

Short Description

To use a single SSH key pair for all your AWS Regions, first generate a public SSH key from a private SSH key. Then, import the key into each of your AWS Regions.

Resolution

If you don't have one already, begin by creating an SSH key pair.

Linux

1.    Generate a public SSH key (.pub) file from the private SSH key (.pem) file:

$ ssh-keygen -y -f MyKeyPair.pem > $HOME/.ssh/id_rsa_MyKeyPair.pub

Note: Replace MyKeyPair.pem with the name of your private .pem file. Make sure that you are working on a bash shell and that the AWS CLI is configured with a user that has valid access.

2.    Run the following command to set the AWS_REGIONS:

$ AWS_REGIONS="$(aws ec2 describe-regions --query 'Regions[].RegionName' --output text)"

3.    Run the following command to import the public SSH key into the Regions:

$ for each_region in ${AWS_REGIONS} ; do aws ec2 import-key-pair --key-name MyKeyPair --public-key-material file://$HOME/.ssh/id_rsa_MyKeyPair.pub --region $each_region ; done

Windows

1.    Generate a public SSH key (.pub) file from the private SSH key (.pem) file:

Open PuTTYgen.

Choose Load to load your private key file.

Choose Save public key.

2.    Import the public SSH key into the desired AWS Regions by running the following commands:

$PubFile = Get-Content .\MyKeyPair.pub -raw
$Key = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($PubFile))
foreach ($Region in (Get-AWSRegion).Region) {Import-EC2KeyPair -KeyName MyKeyPair -PublicKeyMaterial $Key -Region $Region}

Note: Replace MyKeyPair.pub with your public SSH file name.


Did this article help you?

Anything we could improve?


Need more help?