Skip to content

Instantly share code, notes, and snippets.

@zxkane
Created October 16, 2020 07:53
Show Gist options
  • Save zxkane/a12d75947e8e25951bca6d21669aad9d to your computer and use it in GitHub Desktop.
Save zxkane/a12d75947e8e25951bca6d21669aad9d to your computer and use it in GitHub Desktop.
import a local ssh key to all AWS regions
#!/bin/bash -x
import_key() {
local name=$1
local path=$2
local region=$3
EXISTINGKEY=`aws ec2 describe-key-pairs --region $region --key-names $name --query 'KeyPairs[].KeyName' 2>/dev/null|jq '.[]'|jq '.'`
if [[ -z $EXISTINGKEY ]]
then
aws ec2 import-key-pair --key-name $name --public-key-material fileb://$path --region $region >/dev/null
echo "The key with name '$name' already is imported in region '$region'."
else
echo "The key with name '$name' already exists in region '$region'."
fi
}
KEYNAME=$1
KEYPATH=$2
if [[ -z $KEYNAME ]] || [[ -z $KEYPATH ]]
then
echo "pls specify KEYNAME and KEYPATH."
exit -1
fi
export -f import_key
aws ec2 describe-regions --query 'Regions[].RegionName' --output json | jq '.[]'|jq '.'|xargs -I {} -n 1 bash -c 'import_key "$@"' _ "$KEYNAME" "$KEYPATH" {}

Usage

./import-ssh-keys-in-all-regions.sh my-key-pair ~/.ssh/id_rsa.pub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment