Re-using EC2 Key Pair in multiple regions

Re-using EC2 Key Pair in multiple regions

One of the parameters required for launching an EC2 instance is a Key Pair which is effectively an SSH Key used for interactive logging into the default user account – on Amazon Linux it’s the ec-user account – or for decrypting the Windows Administrator’s password.

It is easy to create a new Key Pair / SSH Key as part of the EC2 launch process however as soon as you start using more regions and more accounts you will quickly end up with heaps of stored SSH Keys and unless you are diligent with their naming both on the filesystem an in AWS you’ll end up with a mess. Like I did.

Fortunately there is a way to re-use an existing Key Pair in other regions or even other accounts. And it’s actually pretty easy.

Before we start I assume you’ve got an existing Key Pair or SSH Key, either created by Amazon or your own usual SSH Key created using ssh-keygen. Either will work. Let’s say it’s saved as ~/.ssh/michael.ludvig-key.pem

Importing existing Key Pair

To import this key to a new region go to Services ➞ EC2 ➞ Key Pairs and click Import Key Pair.

Key pair name must be unique within the region (i.e. you can’t have two different keys with the same name) but you should keep it the same between all the regions. Keeping it consistent across regions greatly simplifies your automation – you won’t need a per-region key name mapping.

Now the Public key contents – that’s the part that took me a while to figure out because as of now Amazon provides misleading information both online and in the aws-cli help. The format of the public key must be in RFC4716 format, not in the openssh format starting with ssh-rsa AAAAB3… format that’s suggested by Amazon’s docs yet rejected by the import tool. Convert any of your SSH keys to RFC4716 with this command: