Skip to content

Instantly share code, notes, and snippets.

@philpennock
Last active September 13, 2016 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philpennock/d684558bccf383129b9d81a8abf1a61f to your computer and use it in GitHub Desktop.
Save philpennock/d684558bccf383129b9d81a8abf1a61f to your computer and use it in GitHub Desktop.
Grab SSH hostkeys for a newly launched AWS EC2 instance
#!/bin/sh -eu
#
# Usage:
# aws-instance-sshhostkeys i-deadbeef | tee -a .ssh/known_hosts
# FIXME:
# Strip trailing CR
# Strip trailing comment field
# Support Route53 entries automatically
prog="$(basename "$0")"
if [ $# -eq 0 ]; then
printf >&2 "Usage: %s %s\n" "$prog" "i-deadbeef i-beef2000 | tee -a .ssh/known_hosts"
exit 1
fi
# {{{TestData
output_after=$(( $(date +%s) + 3 ))
testing_dummy_aws() { cat <<'EODUMMY'
{ "Reservations": [
{ "Instances": [
{ "NetworkInterfaces": [
{ "Status": "unwanted", "Association": { "PublicDnsName": "uh-oh", "PublicIp": "192.0.2.1" } },
{ "Status": "in-use", "Association": { "PublicDnsName": "dummyhost", "PublicIp": "192.0.2.42" } }
]
}
]
}
]
EODUMMY
if [ $(date +%s) -ge $output_after ]; then
cat <<'EODUMMY'
, "Output": "lorem ipsum\n-----BEGIN SSH HOST KEY KEYS-----\nssh-rsa 12345dummy54321\nssh-foo wibblepubkey\n-----END SSH HOST KEY KEYS-----\nblah\n"
EODUMMY
fi
echo "}"
}
# }}}TestData
if [ -n "${TESTING_AWS_INSTANCE_SSHHOSTKEYS:-}" ]; then
aws() { testing_dummy_aws "$@" ; }
fi
for instance ; do
prefix=$(
aws ec2 describe-instances --instance-ids "$instance" | \
jq -r '.Reservations[].Instances[].NetworkInterfaces[] | select(.Status == "in-use") | .Association | @text "\(.PublicDnsName),\(.PublicIp)"'
)
printf >&2 "%s: waiting for console log to have output: " "$prog"
loop=true
while $loop ; do
if aws ec2 get-console-output --instance-id "$instance" | jq -e 'has("Output")' > /dev/null
then
printf >&2 " Have Output!\n"
loop=false
else
printf >&2 "."
sleep 5
fi
done
aws ec2 get-console-output --instance-id "$instance" | jq -r .Output | \
perl -ne 'print if /^-----BEGIN SSH HOST KEY KEYS-----\s*$/.../^-----END SSH HOST KEY KEYS-----\s*$/ and not /^-/' | \
while read line; do
printf "%s %s\n" "$prefix" "$line"
done
done
# vim: set sw=2 et foldmethod=marker :
@philpennock
Copy link
Author

hrm, could have sworn that there was a loop around that sleep 5 ... that might have only been in a later version of this where I expanded it further for a previous employer and fixed such bugs. I no longer have access to that, only to this earlier developed-for-self variant.

@philpennock
Copy link
Author

Updated to give it a loop so that it actually waits, and some test data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment