Last active
February 5, 2022 22:10
-
-
Save andresanches/c5d3fe0bad1d3b8d38f523144a203edc to your computer and use it in GitHub Desktop.
update-godaddy-dns.bash
This file contains 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
#! /usr/bin/env bash | |
# | |
# Usage: update-godaddy-dns.sh "api_key" "api_secret" "domain_domain" "domain_name" "log_file" | |
# Note: log_file defaults to /var/log/update-godaddy-dns.log if not provided | |
set -e | |
set -o pipefail | |
log_file="/var/log/update-godaddy-dns.log" | |
log_write() { | |
local message="$1" | |
if [ -n "$message" ]; then | |
echo "$(date '+%Y-%m-%d %H:%M:%S'): $message" \ | |
| tee -a "$log_file" 2> /dev/null | |
fi | |
} | |
log_fatal() { | |
local message="${1}" | |
local exit_code=${2:-1} | |
log_write "$message" | |
exit $exit_code | |
} | |
main() { | |
local curl="curl -sSf --retry 5 --retry-connrefused --retry-delay 1" | |
local api_key="${1:?Missing API key}" | |
local api_secret="${2:?Missing API secret}" | |
local prefix="${3:?Missing domain prefix}" | |
local domain="${4:?Missing domain name}" | |
log_file="${5:-$log_file}" | |
touch "$log_file" &> /dev/null || log_fatal "Cannot write to $log_file" | |
local current_ip="$( | |
nslookup "${prefix}.${domain}" \ | |
| grep '^Address:' \ | |
| grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' | |
)" | |
[ $? -ne 0 ] && log_fatal "Error determining the currently set IP address" | |
local my_ip="$( $curl "http://ipv4.icanhazip.com/" 2>&1 )" | |
[ $? -ne 0 ] && log_fatal "Error querying icanhazip: ${my_ip}" | |
if [ "$current_ip" == "$my_ip" ]; then | |
log_write "No need to update ${prefix}.${domain}. Current IP: ${current_ip}." | |
exit 0 | |
fi | |
# Note: increase the TTL for domains with high traffic. 600 seconds is the lowest godaddy allows. | |
local body="$( printf '[ { "data":"%s", "ttl": 600 } ]' ${my_ip:?} )" | |
local output=$( | |
$curl --header "Authorization: sso-key ${api_key:?}:${api_secret:?}" \ | |
--header 'Accept:application/json' \ | |
--header 'Content-Type: application/json' \ | |
--data "${body:?}" \ | |
"https://api.godaddy.com/v1/domains/${domain:?}/records/A/${prefix:?}" \ | |
2>&1 | |
) | |
[ $? -ne 0 ] && log_fatal "Error updating domain in GoDaddy: ${output}" | |
log_write "Updated domain ${prefix}.${domain} to ${my_ip}" | |
exit 0 | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment