Question

Using the v2 API and my Home Computer to Automatically Update a Domain Name A Record (Like Dynamic DNS)

I want to have a script run automatically on my Mac at home, once an hour, to update the A record of a domain name which lives on DigitalOcean’s name servers.

I want the A record to be updated with whatever my external home IP address is (in effect, a dynamic DNS service so I can always get back to my home computer over the internet). My home computer sits behind a router supplied by my ISP.

I have been looking at the DigitalOcean API (v2) and using Terminal on my Mac I can successfully, manually, update the A record in question with the following command:

curl -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer MY_API_ACCESS_TOKEN" -d '{"data":"IP_ADDRESS"}' "https://api.digitalocean.com/v2/domains/MY_DOMAIN/records/DOMAIN_ID_NUMBER"

What I’d like some help with, please, is how do I add to the above so that:

  • My home external IP address gets ascertained when the script runs,
  • Once ascertained, the IP address is automatically used (in place of ‘IP_ADDRESS’) in the above command, and,
  • The command runs on its own, once an hour.

I’m quite new to all this so I’m sorry if I’m missing anything obvious.

Thanks, any help appreciated.

Show comments

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Just to expand the script above and prevent on each cron trigger to call DO API if IP wasn’t changed:

#!/bin/bash

PUBLIC_IPV4=$(curl ifconfig.co)
SAVED_IPV4=`cat current_ip.txt`

if [ "$PUBLIC_IPV4" != "$SAVED_IPV4" ]
then
echo ${PUBLIC_IPV4} > "current_ip.txt"
curl -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer MY_API_ACCESS_TOKEN" -d '{"data":"'"${PUBLIC_IPV4}"'"}' "https://api.digitalocean.com/v2/domains/MY_DOMAIN/records/DOMAIN_ID_NUMBER"
fi

Here’s an alternative I wrote, which I think is much more secure.

https://github.com/benyanke/configScripts/tree/master/dns-update-server

In this case, the DO api key only exists on a single central API server with this script, and every other host can connect to this api server to inform it of it’s IP. This means your DO keys (which provide complete access to your DO account) are not spread around on multiple hosts.