Digital Ocean Dynamic DNS

Here is bash script to dynamically update DigitalOcean domain name ‘A’ record to create dyndns type service on your Linux system.

Pre-Requisites
1. Domain (example.com) registered at DO
2. Subdomain (home.example.com) which you want to point to a machine whose public IP is not constant
3. DO API key. Can be obtained from https://cloud.digitalocean.com/settings/api/tokens
4. Record ID of subdomain

Now create a file ~/scripts/dnsupdate and copy paste below script. This script gets the public IP and update the A record of subdomain using DigitalOcean API

#!/bin/bash

# your domain ID
domain_name="example.com"

# subdomain
subdomain="home"

# record to update
record_id="12345"

#your api key
api_key="XXXXXXX"

current_date_time="`date '+%Y-%m-%d %H:%M:%S'`";

ip="$(curl  http://ipecho.net/plain)"

if [ -f "ip" ] && [ "$ip" == "$(cat ip)" ] ;then
    result=$current_date_time" match"
else
	echo content="$(curl -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $api_key" -d '{"name": "'"$subdomain"'", "data": "'"$ip"'"}' "https://api.digitalocean.com/v2/domains/$domain_name/records/$record_id")"
    result=$current_date_time" mismatch"	
fi

echo "$result" >> log

To Run it every 10 minutes open crontab

crontab -e 

add below line at the end

*/10 * * * * ~/scripts/dnsupdate

Leave a Reply

Your email address will not be published.