How to use the same SSH key pair in all AWS regions

How to use the same SSH key pair in all AWS regions

In this tutorial I will show you, how to use the same SSH key pair in all AWS regions.

By doing this you can access EC2 instances from different regions using the same SSH key pair.

Installing and configuring AWS CLI

Start by installing and configuring the AWS command line interface:

sudo dnf install awscli
aws configure

Verify the AWS CLI installed correctly:

aws --version
aws-cli/1.11.109 Python/3.6.1 Linux/4.11.10-300.fc26.x86_64 botocore/1.5.72

Configuring the SSH key pair

If you don’t have an SSH key pair or want to follow this article using a new one:

openssl genrsa -out ~/.ssh/aws.pem 2048
ssh-keygen -y -f ~/.ssh/aws.pem > ~/.ssh/

If you already have an SSH private key created using the AWS Console, extract the public key from it:

ssh-keygen -y -f ~/.ssh/aws.pem > ~/.ssh/

Importing the SSH key pair

Now that you have the public key, declare the variable AWS_REGION containing a list with the regions to which you want to copy your SSH key. To check the full list of available AWS regions use this link.

AWS_REGION="us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 eu-central-1 eu-west-1 eu-west-2"

If you don’t want to specify each region manually, you can use the ec2 describe-regions command to get a list of all available regions:

AWS_REGION=$(aws ec2 describe-regions --output text | awk '{print $3}' | xargs)

Next, import the SSH public key to these regions, substituting your key’s name for <MyKey>:

for each in ${AWS_REGION} ; do aws ec2 import-key-pair --key-name <MyKey> --public-key-material file://~/.ssh/ --region each ; done

Also, if you want to display which SSH key is available in a region:

aws ec2 describe-key-pairs --region REGION

To delete an SSH key from a region:

aws ec2 delete-key-pair --key-name <MyKey> --region REGION

Congratulations, now you can use the same SSH key to access all your instances in the regions where you copied it. Enjoy!

Was this Tutorial helpful? Help others share on Facebook, Twitter, and Google Plus!

Enjoyed this video?
How to use the same SSH key pair in all AWS regions
"No Thanks. Please Close This Box!"