Skip to content

Instantly share code, notes, and snippets.

@discordianfish
Created March 12, 2015 13:54
Show Gist options
  • Save discordianfish/81cbe7b8a0a839f7a9e2 to your computer and use it in GitHub Desktop.
Save discordianfish/81cbe7b8a0a839f7a9e2 to your computer and use it in GitHub Desktop.
Tool to update your ssh's known_hosts based on the cloud-init output on AWS EC2
#!/bin/bash
set -e
readonly TMP=$(mktemp)
trap "rm $TMP" EXIT
aws ec2 describe-instances | \
jq -r '.Reservations|map(.Instances)|map(.[])|map([.PrivateIpAddress,.InstanceId])[]|join(",")' | \
while read l
do
ip=$(echo $l | cut -d, -f1)
id=$(echo $l | cut -d, -f2)
fp=$(aws ec2 get-console-output --instance-id $id --output text|awk '/^ec2:.*(ECDSA)/ {print $3}')
echo -n "$ip ($id): "
if [ -z "$fp" ]
then
echo "Skipping, couldn't find fingerprint"
continue
fi
key_file=$(mktemp)
ssh-keyscan -t ecdsa $ip > $key_file 2>/dev/null
if [ ! -s $key_file ]
then
echo "Skipping, couldn't get actual fingerprint"
continue
rm $key_file
fi
actual_fp=$(ssh-keygen -lf $key_file | cut -d' ' -f2)
if [ "$fp" != "$actual_fp" ]
then
echo "Mismatch, expected $fp but got $actual_fp"
rm $key_file
exit 1
fi
echo "Matched, adding key"
ssh-keygen -R $ip &> /dev/null
cat $key_file >> ~/.ssh/known_hosts
rm $key_file
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment