Skip to content

Instantly share code, notes, and snippets.

@janeczku
Last active July 15, 2022 16:32
Show Gist options
  • Save janeczku/6f60b83378ad845f912c to your computer and use it in GitHub Desktop.
Save janeczku/6f60b83378ad845f912c to your computer and use it in GitHub Desktop.
Cron script that updates CloudFront ip ranges for use with nginx real-ip module
#!/bin/bash
# (The MIT License)
#
# Copyright (c) 2015 Jan Broer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
CLOUDFRONT_IP_RANGES_FILE_PATH="/etc/nginx/common/cloudfront.conf"
WWW_GROUP="www-data"
WWW_USER="www-data"
CLOUDFRONT_REMOTE_FILE="https://ip-ranges.amazonaws.com/ip-ranges.json"
CLOUDFRONT_LOCAL_FILE="/var/tmp/cloudfront-ips"
if [ -f /usr/bin/fetch ];
then
fetch $CLOUDFRONT_REMOTE_FILE --no-verify-hostname --no-verify-peer -o $CLOUDFRONT_LOCAL_FILE --quiet
else
wget -q $CLOUDFRONT_REMOTE_FILE -O $CLOUDFRONT_LOCAL_FILE --no-check-certificate
fi
echo "# Amazon CloudFront IP Ranges" > $CLOUDFRONT_IP_RANGES_FILE_PATH
echo "# Generated at $(date) by $0" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
echo "" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
# Parse json and extract CLOUDFRONT IP ranges
RANGES=$(cat $CLOUDFRONT_LOCAL_FILE | jq -r '.prefixes[] | select(.service=="CLOUDFRONT") | .ip_prefix')
# Loop through the ranges, adding each to the file
while read -r line; do
echo "set_real_ip_from $(line);" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
done <<< "$RANGES"
echo "real_ip_header X-Forwarded-For;" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
echo "real_ip_recursive on;" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
echo "" >> $CLOUDFRONT_IP_RANGES_FILE_PATH
chown $WWW_USER:$WWW_GROUP $CLOUDFRONT_IP_RANGES_FILE_PATH
rm -rf $CLOUDFRONT_LOCAL_FILE
@Chathu07
Copy link

Chathu07 commented Jul 15, 2022

Why I'm getting line 48: line: command not found error? Any fix for that?

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