Dynamic DNS with Cloudflare API· 824 words · 5 minutes
DDNS: Dynamic DNS
If you're hosting a service from a location with dynamic DNS (where your IP may change at any time), you must have a solution to update the DNS so that you can access your service even when the IP of the server changes.
The process below uses the Cloudflare API to update DNS
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).
jq since we will use it in the next script:
Next, create a location for your DDNS update scripts and open the first script:
update.sh script will take all of your domains and subdomains and check Cloudflare to see if the current
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= done
Next, open up the
ddns.sh script. Paste the following into the script and update the
⚠️ 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
# 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 fi
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: