Skip to content

Instantly share code, notes, and snippets.

@linosteenkamp
Last active September 6, 2019 08:44
Show Gist options
  • Save linosteenkamp/fc3986f802478c514ba69ea2e8625695 to your computer and use it in GitHub Desktop.
Save linosteenkamp/fc3986f802478c514ba69ea2e8625695 to your computer and use it in GitHub Desktop.
Dynamic Dns update script to update DigitalOcean DNS Zone record
#!/bin/bash
DNS_FILE="$HOME/.my_public_ip"
SUCCESS="200"
DO_API_KEY=""
DO_DOMAIN=""
DO_DNS_RECORD_ID=""
#- Get public ip
ip=$(curl --silent api.ipify.org)
ret=$?
if [ $ret -eq 0 ]; then
#- Read previous ip from file
[ -e "$DNS_FILE" ] && old_ip=$(< "$DNS_FILE" )
#- Update DigitalOcean DNS record if new record differs from previous record
if [ "$ip" != "$old_ip" ]; then
#- Update DigitalOceans DNS Record
result=$(curl \
--silent \
--output /dev/null \
-w %{http_code} \
-H "Authorization: Bearer $DO_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"data\": \"$ip\"}" \
-X PUT "https://api.digitalocean.com/v2/domains/$DO_DOMAIN/records/$DO_DNS_RECORD_ID")
ret=$?
if [ $ret -eq 0 ]; then
if [ "$result" == "$SUCCESS" ]; then
#- Persist new record to file
echo "$ip" > "$DNS_FILE"
logger "$0 - Public ip changed: DNS record updated to $ip"
exit 0
else
logger "$0 - Updating DNS record failed with HTTP error code: $result"
exit 1
fi
else
logger "$0 - Updating public ip failed with curl error code: $ret"
exit 1
fi
fi
logger "$0 - Public ip unchanged: $ip"
exit 0
else
logger "$0 - Retrievieng public ip failed with curl error code: $ret"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment