Skip to content

Instantly share code, notes, and snippets.

@briantully
Last active October 20, 2021 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briantully/41ecac9f011a8330b10792e99aa38612 to your computer and use it in GitHub Desktop.
Save briantully/41ecac9f011a8330b10792e99aa38612 to your computer and use it in GitHub Desktop.
AWS EC2 Instances IP Ranges by Region
#!/usr/bin/env bash
# Call AWS endpoint for IP Ranges and filter by service (EC2) and region
# @author Brian Tully <brian.tully@acquia.com>
usage ()
{
echo "-----------------------------------------------------------------------"
echo "usage: $0 'REGION'"
echo "where 'REGION' is the AWS region name, e.g. 'us-east-1'"
echo "A JSON file of filtered AWS EC2 IP ranges will be saved to $HOME/Desktop/AWS-IP-RANGES/[REGION]-[TIME].json"
echo "-----------------------------------------------------------------------"
exit
}
# if no REGION arg is specified, display USAGE prompt
if [ -z "$1" ]
then
usage
else
REGION=$1
fi
# write IP Ranges out to a JSON file within a folder on your Desktop
FILEDIR="${HOME}/Desktop/AWS-IP-RANGES"
if [ ! -d $FILEDIR ]; then
mkdir -p $FILEDIR
fi
# get current time so we can append it to filename
CURRENT_TIME=$(date +"%Y-%m-%d_%H-%M-%S")
# CSV file gets stored on user's desktop (for now)
FPATH="${FILEDIR}/${REGION}-${CURRENT_TIME}.json"
echo "Retrieving a list of IP Ranges for AWS EC2 instances within region '${REGION}'..."
# run curl to AWS endpoint for IP ranges and parse JSON with jq
# filter by reqion
curl -s https://ip-ranges.amazonaws.com/ip-ranges.json | \
jq "[ .prefixes[] | select( (.service | contains(\"EC2\")) and (.region | contains(\"${REGION}\")) ) ]" >> $FPATH
sleep 1
COUNT=$(jq '. | length' $FPATH)
echo "${COUNT} AWS EC2 IP Ranges were found for region '${REGION}'."
echo "----------------------------------------------------------------------"
echo "The JSON file with filtered results can be found at:"
echo "'${FPATH}'"
echo "DONE! :)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment