Re-using EC2 SSH Key Pair in multiple AWS regions

Michael Ludvig
Jul 16 · 4 min read
Image for post
Image for post
Photo by Samantha Lam on Unsplash

Importing existing Key Pair

Image for post
Image for post
~ $ ssh-keygen -e -m RFC4716 -f ~/.ssh/michael.ludvig-key.pem
Enter passphrase: ****
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "2048-bit RSA, converted by michael.ludvig from Open"
AAAAB3NzaC1yc2EAAAADAQABAAABAQC3Y5e3oNnxHXZAAPMHjlxuzhXnqt+3q2
HdF3HZskjKlFIjW83iBPcAsMi3sf0CGnFvcP0U9o6MAXHhLtKIEjmybAfNP/AJ
[...]
u9RxTR1zR87JY4D8w5vFQMXyjj/6p2xRyTwwCHVcU92mxARi4ipjH27uM8SpVj
a2mi2HkhsWtDA6JIkd1qpogtj
---- END SSH2 PUBLIC KEY ----
Image for post
Image for post
Image for post
Image for post

Importing with AWS-CLI

~ $ ssh-keygen -e -m RFC4716 -f ~/.ssh/michael.ludvig-key.pem > michael.ludvig-key.pub
~ $ aws --region=xy-abcd-1 \
ec2 import-key-pair \
--key-name=michael.ludvig-key \
--public-key-material=file://michael.ludvig-key.pub
{
"KeyName": "michael.ludvig-key",
"KeyFingerprint": "ab:9c:38:ef:4b:99:1e:b1:f6:60:e6:fe:a5:fc:10:fa"
}
A client error (InvalidKey.Format) occurred when calling the ImportKeyPair operation: Key is not in valid OpenSSH public key format

Importing to all regions

~ $ for REGION in $(aws --output text ec2 describe-regions --query 'Regions[].RegionName[]'); do
echo "== ${REGION} =="
aws --region=${REGION} ec2 import-key-pair \
--key-name=... --public-key-material=...
done

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store