Skip to content

Instantly share code, notes, and snippets.

@achetronic
Created July 2, 2022 19:23
Show Gist options
  • Save achetronic/63fd31e0bb8df88871f8fd5cc1386777 to your computer and use it in GitHub Desktop.
Save achetronic/63fd31e0bb8df88871f8fd5cc1386777 to your computer and use it in GitHub Desktop.
Add an SSH key to all EC2 machines on AWS
#!/usr/bin/env bash
AWS_ENVIRONMENT="production"
SSH_PUBLIC_KEY="ssh-ed25519 XXXYYYZZZexampleXXXYYYZZZ/XYZXYZ your.email@your.company.com"
# Copy the key to a temporary location
touch /tmp/id_ed25519.pub
echo "${SSH_PUBLIC_KEY}" > /tmp/id_ed25519.pub
# See all machines in all regions
for region in `aws ec2 describe-regions --profile "${AWS_ENVIRONMENT}" --region us-east-1 --output text | cut -f4`
do
echo -e "\nListing Instances in region:'$region'..."
REGION_MACHINES=$(aws ec2 describe-instances \
--profile "${AWS_ENVIRONMENT}" \
--region $region \
--query "Reservations[*].Instances[*].PublicIpAddress" \
--output json \
--no-paginate \
--no-cli-pager | jq 'flatten' | tr -d '[]" ')
# Authorize the public key inside each machine
for machine in $REGION_MACHINES; do
machine=$(echo "${machine}" | tr -dc '[:alnum:]-.')
echo "Authorizing SSH key inside machine: ${machine}"
#cat /tmp/id_ed25519.pub
ssh-copy-id -f -i /tmp/id_ed25519.pub -o ConnectTimeout=10 -p 22 your-user@"${machine}"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment