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

2 minute read
0

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

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshoot AWS CLI errors. Also, make sure that you're using the most recent AWS CLI version.

If you don't have an EC2 SSH key pair yet, then create one.

To use the SSH key pair to access your instances in all your Regions, complete the following procedure for your operating system.

Linux

Complete the following steps:

  1. To generate a public SSH key (.pub) file from the private SSH key (.pem) file, run the following command:

    $ 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 work on a bash shell and that you configure the AWS CLI with a user that has valid access.

  2. To set the Regions, run the describe-regions command:

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

    Note: If you use a ZSH shell, then run the following command to activate word splitting so that the for loop command correctly iterates each Region name:

    $ setopt shwordsplit
  3. To import the public SSH key pair into the Regions, run the import-key-pair command:

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

Windows

Complete the following steps:

  1. To generate a public SSH key (.pub) file from the private SSH key (.pem) file, do the following:
    Open PuTTYgen.
    Choose Load to load your private key file.
    Choose Save public key.

  2. To import the public SSH key pair into the Regions, run the following command:

    $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.

Related information

AWS service endpoints

Import-EC2KeyPair Cmdlet

AWS OFFICIAL
AWS OFFICIALUpdated 6 months ago