Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@RalphORama
Last active October 24, 2017 23:29
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 RalphORama/154996ea3b9c3e110364193df25de8d1 to your computer and use it in GitHub Desktop.
Save RalphORama/154996ea3b9c3e110364193df25de8d1 to your computer and use it in GitHub Desktop.
Update CF-Connecting-IP lists for NGINX automatically
#!/usr/bin/env python3
# I personally use a crontab to execute this at midnight, daily
# # m h dom mon dow command
# 0 0 * * * /usr/bin/python3 /usr/local/sbin/cloudflare-nginx-resolver.py > /etc/nginx/snippets/cloudflare-realip.conf && nginx -t && systemctl restart nginx
# Then, in virtual hosts that need this config, I simply add the line
# include /etc/nginx/snippets/cloudflare-realip.conf
import requests
from sys import exit
# Fill out your Mailgun account info and set mail_enabled to True if
# you'd like automatic emails if this script fails.
mail_enabled = False
domain = 'YOUR_MAILGUN_SANDBOX_OR_DOMAIN'
sender = 'YOUR_SENDER_ADDRESS'
apikey = 'YOUR_MAILGUN_KEY'
recipient = 'YOUR_EMAIL_ADDRESS'
def send_email(message: str):
if not mail_enabled:
return
request_url = 'https://api.mailgun.net/v3/{}/messages'.format(domain)
try:
request = requests.post(request_url, auth=('api', apikey), data={
'from': sender,
'to': recipient,
'subject': 'NGINX CloudFlare Resolver Update Error',
'text': message
})
except Exception as e:
# TODO: Handle this some interesting way
raise(e)
return
def process_response_text(text: str, prefix='', postfix=''):
formatted_text = ''
for line in text.splitlines():
formatted_text = formatted_text + '{0}{1}{2}'.format(prefix, line, postfix) + '\n'
return formatted_text
if __name__ == '__main__':
try:
v4_ips = requests.get('https://www.cloudflare.com/ips-v4', timeout=1)
v6_ips = requests.get('https://www.cloudflare.com/ips-v6', timeout=1)
except Exception as e:
send_email("""The Cloudflare NGINX resolver encoundered an error when attempting to fetch a list of IPs.
The error code is reproduced here:\n\n {}\n
Please check your logs and config files to make sure everything is ok.
""".format(e))
exit(1)
if not (v4_ips.status_code == v6_ips.status_code == 200):
# TODO: Send me an email or something instead of failing silently
send_email("""The Cloudflare NGINX resolver encoundered an error when attempting to fetch a list of IPs.
The request encoundered the following response codes:\n
v4 IPs: {}
v6 IPs: {}\n
Please check your logs and config files to make sure everything is ok.
""".format(v4_ips.status_code, v6_ips.status_code))
exit(2)
print(process_response_text(v4_ips.text, 'set_real_ip_from ', ';'))
print(process_response_text(v6_ips.text, 'set_real_ip_from ', ';'))
print('# use any of the following two',
'real_ip_header CF-Connecting-IP;',
'#real_ip_header X-Forwarded-For;', sep='\n')
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment