I needed to dump configuration of our DNS zones hosted in Cloudflare. As this is going to be repetitive task I wanted to automated it.
After a quick search I’ve found some PoSh modules to work with Cloudflare but it seems they’re a bit outdated. Because I needed to dump all DNS entries of all zones I decided to use their API directly.
The main idea is to connect to Cloudflare API (https://api.cloudflare.com) and query for all zones. For each zone prepare an object and with current settings and all DNS entries. Then, dump each zone into JSON file. This is stored in our GIT repo.
- Step one – Cloudflare requires TLS 1.2 for API connection. This is set with this statement during script execution:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
- Step two – authenticate to Cloudflare API:
- Step three – list all zones and get their ID. This is a simple Invoke-RestMethod:
-URI “https://api.cloudflare.com/client/v4/zones/?match=all” -Method Get -Headers $CloudFlareHeaders
- Step four – list all dns entries for specific zone. Another simple Invoke-RestMethod:
-URI “https://api.cloudflare.com/client/v4/zones/ZONEID/dns_records?match=all” -Method Get -Headers $CloudFlareHeaders
Let’s combine it into something more useful. I’ve wrapped this into a function that accepts three parameters: API token, e-mail address/login and destination folder.
After successful authentication it will enumerate all zones and save their configuration into a hashtable. Then using zone id it will enumerate all DNS entries and add it into the hashtable. Then the hashtable will be saved as JSON file (name of the file will be zone name).
Thanks to this I can plug it into our CI, inject tokens (API, e-mail, folder) on the fly, get the configuration and afterwards commit to GIT. Without much of my attention! Now, even before we switch to full DNS as a Code (great article by Kieran Jacobsen here) we can control if any changes were made to our configuration with ease!