Last active
October 18, 2024 06:26
-
-
Save V1ncNet/cc7615c6b6bde7248d6c5bc9e0335d6d to your computer and use it in GitHub Desktop.
Update a DNS record dynamically on DigitalOcean with a Shell Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| ######################################################################### | |
| # # | |
| # DNS Record Updater # | |
| # # | |
| # Purpose: Update a DNS Record on DigitalOcean via the DigitalOcean API # | |
| # # | |
| # Description: This script retreive the current public IP address which # | |
| # will be stored in the .curip file. If the curled address # | |
| # doesn't match its former value from the file the script # | |
| # sends a PUT request to the DigitalOcean API to update an # | |
| # A record. The current public IP got stored in the .curip # | |
| # file afterwards. # | |
| # # | |
| # Usage: Insert your API key, domain id and domain name an run the # | |
| # script. Don't forget to run chmod +x update-do-dns.sh before. # | |
| # # | |
| # Usecase: I want to access my local network from the internet via a # | |
| # domain name. Crontab executes this script every 15 minutes # | |
| # on my Raspberry Pi. # | |
| # # | |
| ######################################################################### | |
| TOKEN="" # <- Insert your DO API key here | |
| DOMAIN_ID="" # <- Insert your domain id here | |
| DOMAIN="" # <- Insert your domain name here | |
| PWD="$(dirname $0)" | |
| FILE="$PWD/.curip" | |
| if [ -e "$FILE" ]; then | |
| CURRENT_IP=$(awk '{print $1;}' $FILE) | |
| else | |
| echo " *** $FILE does not exist. Creating a new one" | |
| touch $FILE | |
| fi | |
| echo " *** Curl for current public IP address" | |
| IP="$(curl -s -m 60 http://ipecho.net/plain)" | |
| if [ $? -ne 0 ]; then | |
| echo " --- Timeout. The operation took too long" | |
| exit 1 | |
| fi | |
| if [ "$IP" == "$CURRENT_IP" ]; then | |
| echo " *** Ok. Current IPv4 matches curled IP address" | |
| else | |
| echo " *** Send PUT request to DigitalOcean API v2" | |
| curl -s -m 60 -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"id":"'"$DOMAIN_ID"'", "data":"'"$IP"'"}' "https://api.digitalocean.com/v2/domains/$DOMAIN/records/$DOMAIN_ID" | |
| if [ $? -ne 0 ]; then | |
| echo " --- Timeout. The operation took too long" | |
| exit 1 | |
| fi | |
| echo | |
| echo " *** Write new public IPv4 to $FILE" | |
| echo $IP > $FILE | |
| echo " *** Ok. Sucessfully updated DNS record" | |
| fi | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment