Dynamic DNS Updates via the Cloudflare API
· Automatically updating DNS A and AAAA records via the Cloudflare API.
Table of Contents
1. DDNS: Dynamic DNS
If you're hosting a service from a location with DDNS (Dynamic Domain Name System), where your internet protocol (IP)address may change at any time, you must have a solution to update the DNS (Domain Name System) so that you can access your service even when the IP of the server changes.
The process below uses the Cloudflare API (application programming interface) to update DNS A and AAAA records with the server's current IP. If you use another DNS provider, you will have to find a way to update your DNS (or find a way to get a static IP).
First, install jq since we will use it in the next script:
Next, create a location for your DDNS update scripts and open the first script:
The following update.sh script will take all of your domains and subdomains and check Cloudflare to see if the current A and AAAA records match your server's IP address. If not, it will update the records.
# file: update.sh
#!/bin/bash
# Update TLDs
domains=(example.com example.net)
for
do
zone_name=
done
# Update subdomains for example.com
domain=example.com
subdomains=(photos.example.com)
for
do
zone_name= dns_record=
Next, open up the ddns.sh script. Paste the following into the script and update the api_token and email variables.
Note: If you want your DNS records to be proxied through Cloudflare, find and update the following snippet: "proxied":false}" to say true instead of false.
# file: ddns.sh
#!/bin/bash
# based on https://gist.github.com/Tras2/cba88201b17d765ec065ccbedfb16d9a
# initial data; they need to be filled by the user
## API token
api_token=<YOUR_API_TOKEN>
## email address associated with the Cloudflare account
email=<YOUR_EMAIL>
# get the basic data
ipv4=
ipv6=
user_id=
# check if the user API is valid and the email is correct
if [
then
zone_id=
# check if the zone ID is
if [
then
# check if there is any IP version 4
if [
then
dns_record_a_id=
# if the IPv6 exist
dns_record_a_ip=
if [
then
# change the A record
|
else
fi
else
fi
# check if there is any IP version 6
if [
then
dns_record_aaaa_id=
# if the IPv6 exist
dns_record_aaaa_ip=
if [
then
# change the AAAA record
|
else
fi
else
fi
else
fi
else
Once the script is saved and closed, make the scripts executable:
You can test the script by running it manually:
To make sure the scripts run automatically, add it to the cron file so that it will run on a schedule. To do this, open the cron file:
In the cron file, paste the following at the bottom of the editor: