Skip to content

Instantly share code, notes, and snippets.

@akrizs
Created May 21, 2018 00:40
Show Gist options
  • Save akrizs/bccdf69af52c3edbc5d8a6cad11e1e8c to your computer and use it in GitHub Desktop.
Save akrizs/bccdf69af52c3edbc5d8a6cad11e1e8c to your computer and use it in GitHub Desktop.
DigitalOcean Dynamic DNS Updater
#!/bin/bash
# Function to split out the json value fetched from DigitalOcean to parse out just the IP adress.
# You have to install jq for this to work, the parsing of the current stored ip depends on it: https://stedolan.github.io/jq/
function extractip {
temp=`echo $ip_received | jq -r '.domain_record.data'`
echo ${temp}
};
# Your domain name
domain="YOUR-DOMAIN"
# Record ID to update (subdomain)
record="YOUR-DNS-RECORD"
# API Key.
api_key="YOUR-DIGITAL-OCEAN-API-KEY"
# Feth ip from external source.
current_ip=$(curl ifconfig.co)
# Fetch IP from interface.
#current_ip="$(ifconfig re0 | grep -E 'inet.[0-9]' | grep -v '127.0.0.1'| awk '{
#print $2}')"
##### Fetch current IP stored on Digital Ocean.
# Fetch the json object.
ip_received="$(curl \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $api_key" \
-X GET "https://api.digitalocean.com/v2/domains/$domain/records/$record")"
# Run the json parsing script and get the value of {data:"ipaddress"}.
stored_ip=$(extractip)
if [ "$current_ip" = "$stored_ip" ]
then
echo "No update needed"
echo $stored_ip
echo $current_ip
else
echo ip_sent="$(curl \
-k \
-H "Authorization: Bearer $api_key" \
-H "Content-Type: application/json" \
-d '{"data": "'"$current_ip"'"}' \
-X PUT "https://api.digitalocean.com/v2/domains/$domain/records/$record")"
fi
@akrizs
Copy link
Author

akrizs commented May 21, 2018

My first GIST

My first shell script

Banged my head around for couple of hours (Currently learning JavaScript and Nodejs, not this!)

This is based of a couple of snippets from here and there, I use it on my pfSense to dynamically update my IP address so i always have access to my network over VPN.

Please throw me a comment if you see any modifications that could be done.
2 methods to fetch IP address, the one enabled in this script is fetching it from an outside source, can be useful if you are double nat-ed, the other is to fetch the ip directly from your ifconfig, you just have to edit the re0 to correct interface identifier.

The biggest difference is that the script starts with fetching the IP already stored on the domain record and then compares it to your current IP address, if they match then the script does nothing and dies, if they don't match then it sends an update with you current IP to be updated on the record.

You should have jq installed on your system for this too work

When setting up on pfSense you install cron on you gateway, they you set the command to run with bash in front

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment