/cloudflare-ddns

Script for dynamically updating a CloudFlare DNS record.

Primary LanguagePython

cloudflare-ddns

Introduction

A script for dynamically updating a CloudFlare DNS record. I use CloudFlare to host DNS for a domain and I wanted to point an A record in that domain to a host who's IP address changes occasionally. CloudFlare has an API to do this, so this happened.

Dependencies

You'll need a python interpreter and the following libraries:

Usage

First, a few assumptions:

  • You have a CloudFlare account.
  • You're using CloudFlare to host DNS for a domain you own.
  • You have an A record in CloudFlare you intend to dynamically update.

To use this utility, create a copy of the config.yaml.template file (and remove .template from the filename). Create one template per each record / domain pair you intend to update. For example, I might have two configuration files: mattslifebytes_naked.yaml that updates the A record for the naked (no www prefix) domain mattslifebytes.com, and a second config, mattslifebytes_www.yaml that updates the A record for www.mattslifebytes.com

To do a one-off update of your DNS record, simply run python cloudflare_ddns.py config_file_name.yaml from your terminal. The script will determine your public IP address and automatically update the CloudFlare DNS record along with it.

If the program encounters an issue while attempting to update CloudFlare's records, it will print the failure response CloudFlare returns. Check your configuration file for accurate information and try again.

Because dynamic IPs can change regularly, it's recommended that you run this utility periodically in the background to keep the CloudFlare record up-to-date.

Just add a line to your crontab and let cron run it for you at a regular interval.

# Every 15 minutes, check the current public IP, and update the A record on CloudFlare.
*/15 * * * * /path/to/code/cloudflare-ddns.py /path/to/code/mattslifebytes_www.yaml >> /var/log/cloudflare_ddns.log

This example will update the record every 15 minutes. You'll want to be sure that you insert the correct paths to reflect were the codebase is located. The redirection (>>) to append to a log file is optional, but handy for debugging if you notice the DNS record is not staying up-to-date.

If you want to learn more about the CloudFlare API, you can read on here.

Credits and Thanks

  • CloudFlare for having an API and otherwise generally being cool.
  • icanhazip.com for making grabbing your public IP from a script super easy.