Sunday, December 11, 2016

How-To: Dynamically Updating Cloudflare DNS on EdgeRouter

Cloudflare is an awesome DNS, CDN and  security provider but they don't offer a Dynamic DNS feature.  For anyone running services from their home or on an ISP that doesn't offer static IP addresses, you might think you're out of luck with Cloudflare.  What you might not be aware of is that Cloudflare has an API that can be utilized to perform all sorts of actions.  One such action is updating a host record (or records).

I've seen several how-to articles to accomplish this but most of them are a few years old and no longer work with the newer firmware.  This how-to will walk you through setting up a scheduled task on an Ubiquiti ER-X, although it will probably work on any router running EdgeOS.  My router at the time of this article is an ER-X running FW 1.9.0

Step 1

You'll need to run this Curl command to get the ID of the host record that you want to update.  In case you aren't aware, you can just run this right from your router.  Just SSH in and issue the command.

Modify it to match your Cloudflare account.  You'll get a big long JSON response back but you can copy it into a JSON parser to make it easier to read.  Here is the one I used.

JSON Parser

You need to find the rec_id for the host record that you want to modify.  Copy the ID for use in our update script.

Step 2

Create a shell script which will be used to run the update command.  This is what I'm using, just copy it into a new file and save as or whatever you want to name it.  You'll need to modify it to match your Cloudflare account.  You need to save it to /config/scripts so that it persists between firmware upgrades.  Don't forget to chmod a+x the file to make it executable.

Step 3

Next we need to create a scheduled task on our EdgeRouter to run the update script.  The GUI for this isn't very good and the CLI is much easier for getting this done.  Again we'll need to SSH into the router and then enter configure mode.  Assuming you've kept the file names the same as what I'm using, you can just copy the commands below and run them.  This will create the scheduled task and have it run every 24 hours.  You can change the interval to a shorter time if you are worried your IP address might change more often.  Typically every 24 hours should be sufficient though.

You can manually test this by setting your A record to an incorrect IP address and then running the script.