Skip to content

Instantly share code, notes, and snippets.

@jogaco
Created May 15, 2017 15:28
Show Gist options
  • Save jogaco/3e242468f55d80eb35663f7f15a80606 to your computer and use it in GitHub Desktop.
Save jogaco/3e242468f55d80eb35663f7f15a80606 to your computer and use it in GitHub Desktop.
Cloudflare: automatic update of IP addresses
#!/bin/bash
# Location of the nginx config file that contains the CloudFlare IP addresses.
CF_NGINX_CONFIG="/etc/nginx/cloudflare-real-ip.conf"
CF_NGINX_CONFIG_NEW="/etc/nginx/cloudflare-real-ip.conf.new"
# The URLs with the actual IP addresses used by CloudFlare.
CF_URL_IP4="https://www.cloudflare.com/ips-v4"
CF_URL_IP6="https://www.cloudflare.com/ips-v6"
# Temporary files.
CF_TEMP_IP4="/tmp/cloudflare-ips-v4.txt"
CF_TEMP_IP6="/tmp/cloudflare-ips-v6.txt"
# Download the files.
if [ -f /usr/bin/curl ];
then
curl --silent --output $CF_TEMP_IP4 $CF_URL_IP4
curl --silent --output $CF_TEMP_IP6 $CF_URL_IP6
elif [ -f /usr/bin/wget ];
then
wget --quiet --output-document=$CF_TEMP_IP4 --no-check-certificate $CF_URL_IP4
wget --quiet --output-document=$CF_TEMP_IP6 --no-check-certificate $CF_URL_IP6
else
echo "Unable to download CloudFlare files."
exit 1
fi
# Generate the new config file.
echo "# CloudFlare IP Ranges" > $CF_NGINX_CONFIG_NEW
echo "# Generated by $0" >> $CF_NGINX_CONFIG_NEW
echo "" >> $CF_NGINX_CONFIG_NEW
echo "# - IPv4 ($CF_URL_IP4)" >> $CF_NGINX_CONFIG_NEW
awk '{ print "set_real_ip_from " $0 ";" }' $CF_TEMP_IP4 >> $CF_NGINX_CONFIG_NEW
echo "" >> $CF_NGINX_CONFIG_NEW
echo "# - IPv6 ($CF_URL_IP6)" >> $CF_NGINX_CONFIG_NEW
awk '{ print "set_real_ip_from " $0 ";" }' $CF_TEMP_IP6 >> $CF_NGINX_CONFIG_NEW
echo "" >> $CF_NGINX_CONFIG_NEW
echo "real_ip_header CF-Connecting-IP;" >> $CF_NGINX_CONFIG_NEW
echo "" >> $CF_NGINX_CONFIG_NEW
# Remove the temporary files.
rm $CF_TEMP_IP4 $CF_TEMP_IP6
cmp -i=70 ${CF_NGINX_CONFIG_NEW} ${CF_NGINX_CONFIG} >/dev/null 2>&1
comp_val=$?
if [ $comp_val -eq 1 ];
then
echo "Cloudflare config file is different"
# Copy new file onto config file
cp $CF_NGINX_CONFIG_NEW $CF_NGINX_CONFIG
# Reload the nginx config.
service nginx reload
else
echo "Cloudflare config file is NOT different"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment