Last active
October 24, 2017 18:41
-
-
Save mdlavin/ec69bec1cbbcdba7a602 to your computer and use it in GitHub Desktop.
Build SSH config Hosts line from AWS subnet query
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
#!/bin/bash | |
# If your AWS account has a lot of subnets and you want to have an SSH config entry for all of the subnets, then | |
# building the Hosts line by hand can be quite cumbersome. This script will automatically fetch the subnets | |
# from AWS for your account and build a Hosts line with wildcards to cover all of the IP ranges | |
ALL="" | |
for CIDR in `aws ec2 describe-subnets --query Subnets[].CidrBlock --output text`; do | |
#echo $CIDR | |
HOST_MIN=$(ipcalc $CIDR | ggrep -Po '(?<=HostMin:)[ ]*([^ ]*)' | sed 's/ //g') | |
HOST_MAX=$(ipcalc $CIDR | ggrep -Po '(?<=HostMax:)[ ]*([^ ]*)' | sed 's/ //g') | |
#echo "Min: \"$HOST_MIN\"" | |
#echo "Max: \"$HOST_MAX\"" | |
ENDS_WITH_MIN="\.1$" | |
ENDS_WITH_MAX="\.254$" | |
if [[ $HOST_MIN =~ $ENDS_WITH_MIN ]] && [[ $HOST_MAX =~ $ENDS_WITH_MAX ]]; then | |
#echo "Easy min/max" | |
CURRENT=$(echo $HOST_MIN | sed 's/[0-9]*\.[0-9]*\.\([0-9]*\)\.[0-9]*/\1/' ) | |
END=$(echo $HOST_MAX | sed 's/[0-9]*\.[0-9]*\.\([0-9]*\)\.[0-9]*/\1/' ) | |
PREFIX=$(echo $HOST_MIN | sed 's/\([0-9]*\.[0-9]*\.\)[0-9]*\.[0-9]*/\1/' ) | |
PREFIX_MAX=$(echo $HOST_MAX | sed 's/\([0-9]*\.[0-9]*\.\)[0-9]*\.[0-9]*/\1/' ) | |
if [ "$PREFIX" != "$PREFIX_MAX" ]; then | |
echo "Unsupported mismatching min/max prefixes: $PREFIX $PREFIX_MAX" | |
exit 1 | |
fi | |
#echo Start $CURRENT | |
#echo End $END | |
while [ "$CURRENT" -le "$END" ]; do | |
#echo "${PREFIX}${CURRENT}.*" | |
ALL="$ALL ${PREFIX}${CURRENT}.*" | |
CURRENT=$((CURRENT+1)) | |
done | |
fi | |
done | |
echo "SSH host line should be: $ALL" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment