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

2 minute read

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.

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.


If you don't have one already, create an SSH key pair.


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

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

Note: Replace MyKeyPair.pem with the name of your private .pem file. Make sure that you're working on a bash shell and that you configure the AWS CLI 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)"

Note: If you're using a ZSH shell, enable word splitting so that the for loop command iterates each Region name properly. Use the following commands to enable word splitting:

$ setopt shwordsplit

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 fileb://$HOME/.ssh/ --region $each_region ; done


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 .\ -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 with your public SSH file name.

Related information

AWS CLI Command Reference - import-key-pair

AWS service endpoints

Import-EC2KeyPair Cmdlet

AWS OFFICIALUpdated 3 years ago