Skip to content

Instantly share code, notes, and snippets.

@jasonmimick
Last active April 20, 2021 17:56
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 jasonmimick/14b5af53540ed80ecc12f0436957bb95 to your computer and use it in GitHub Desktop.
Save jasonmimick/14b5af53540ed80ecc12f0436957bb95 to your computer and use it in GitHub Desktop.
Add all AWS IP ranges to a MongoDB Atlas Org api key access list
#!/usr/bin/env bash
#PUBLIC_KEY=${1:-${ATLAS_PUBLIC_KEY}}
#PRIVATE_KEY=${1:-${ATLAS_PRIVATE_KEY}}
#ORG_ID=${1:-${ATLAS_ORG_ID}}
#
# aws-access-lister.sh
#
# This utility script can be used to maintain the Access List for
# a MongoDB Atlas Programatic API Key. For example, when running on AWS lambda
# the IP-address of the host is not know beforehand and thus it's not possible to
# securly configure an api key. This script will dynamically fetch a valid set of
# IP ranges directly from AWS and then either create a new apikey or modify an existing key
# with all the IP ranges.
#
# This tool requires `mongocli` to be installed and configured with
# an appropriatly scopre apikey (ORG_OWNER).
#
# Options - set via environment variables only
# REGION - default 'us-east-1', use valid AWS regions
# SERVICE - list of services to allow default 'AMAZON,CODEBUILD', possible values:
#AMAZON,AMAZON_APPFLOW,AMAZON_CONNECT,API_GATEWAY,CHIME_VOICECONNECTOR,CLOUD9,CLOUDFRONT,CODEBUILD,DYNAMODB,EC2,EC2_INSTANCE_CONNECT,GLOBALACCELERATOR,KINESIS_VIDEO_STREAMS,ROUTE53_HEALTHCHECKS,ROUTE53_HEALTHCHECKS_PUBLISHING,S3,WORKSPACES_GATEWAYS,
#
# Usage:
# This tool will produce a set of mongocli commands
# you can run as a script to add apikey accesslist entries
# for known AWS ip ranges.
#
TARGET_APIKEY_PUBLIC_KEY="${1}"
if [ -z "$TARGET_APIKEY_PUBLIC_KEY" ]
then
echo "usage: ./aws-access-lister.sh <TARGET_APIKEY_PUBLIC_KEY>"
exit 1
fi
echo "## TARGET_APIKEY_PUBLIC_KEY:${TARGET_APIKEY_PUBLIC_KEY}"
TARGET_APIKEY_ID=$(mongocli iam organizations apikeys list --output json | \
jq -r --arg tpk "${TARGET_APIKEY_PUBLIC_KEY}" \
'.[] | select(.publicKey == $tpk) | .id')
echo "## TARGET_APIKEY_ID:${TARGET_APIKEY_ID}"
if [ -z "$REGION" ]
then
region=${2:-us-east-1}
else
region=${2:-${REGION}}
fi
if [ -z "$REGION" ]
then
services=${3:-AMAZON,CODEBUILD}
else
services=${3:-${SERVICES}}
fi
echo "## region=${region}, services=${services}"
if [ -f ip-ranges.json ]
then
cp ip-ranges.json{,$(date --iso-8601=seconds)}
fi
curl -skOL https://ip-ranges.amazonaws.com/ip-ranges.json > ip-ranges.json
cat ip-ranges.json | \
jq --arg reg "${region}" \
--arg svcs "${services}" \
'.prefixes[] | select((.region == $reg) and (.service | inside($svcs))) | .' | \
jq --slurp '.' | \
jq '.[] | .ip_prefix' | \
xargs -I {} echo "mongocli iam organizations apikeys whitelists create --apiKey ${TARGET_APIKEY_ID} --cidr {}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment