Created
July 2, 2022 19:23
-
-
Save achetronic/63fd31e0bb8df88871f8fd5cc1386777 to your computer and use it in GitHub Desktop.
Add an SSH key to all EC2 machines on AWS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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