forked from acabal/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-digital-ocean-dns-record
executable file
·71 lines (57 loc) · 2.13 KB
/
update-digital-ocean-dns-record
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/sh
usage(){
fmt <<EOF
DESCRIPTION
Check if the IP address of this host matches the DNS records of a remote host. If it doesn't match, update the DNS records using the Digital Ocean API.
USAGE
update-digital-ocean-dns-record -d,--domain=DOMAIN -s,--subdomain=SUBDOMAIN -k,--api-key=DIGITALOCEANAPIKEY
EOF
exit
}
die(){ printf "Error: ${1}\n" 1>&2; exit 1; }
require(){ command -v $1 > /dev/null 2>&1 || { suggestion=""; if [ ! -z "$2" ]; then suggestion=" $2"; fi; die "$1 is not installed.${suggestion}"; } }
if [ $# -eq 1 ]; then if [ "$1" = "--help" -o "$1" = "-h" ]; then usage; fi fi
#End boilerplate
require "curl" "Try: apt-get install curl"
require "jq" "Try: apt-get install jq"
apiKey=""
domain=""
subdomain=""
for i in "$@"
do
case "${i}" in
-d=*|--domain=*)
domain="$(echo ${i} | sed 's/[-a-zA-Z0-9]*=//')"
;;
-k=*|--api-key=*)
apiKey="$(echo ${i} | sed 's/[-a-zA-Z0-9]*=//')"
;;
-s=*|--subdomain=*)
subdomain="$(echo ${i} | sed 's/[-a-zA-Z0-9]*=//')"
;;
esac
done
if [ "${apiKey}" = "" -o "${domain}" = "" -o "${subdomain}" = "" ]; then
usage
fi
#look up the existing dns entry
dnsIp=$(dig +short "${domain}")
if [ "${dnsIp}" = "" ]; then
die "Couldn't resolve ${domain} while looking up DNS records."
fi
#look up our external ip
localIp=$(curl ifconfig.me 2> /dev/null)
if [ $? -ne 0 ]; then
die "Couldn't resolve ifconfig.me while looking up local IP."
fi
if [ "${dnsIp}" != "${localIp}" ]; then
#Get the record ID from Digital Ocean
subdomainId=$(curl --silent --request GET --header "Content-Type: application/json" --header "Authorization: Bearer ${apiKey}" "https://api.digitalocean.com/v2/domains/${domain}/records" | jq ".[] | . [] | select(.name==\"${subdomain}\")" 2>/dev/null | grep "id" | sed --regexp-extended "s/[^0-9]//g")
if [ $? -ne 0 ]; then
die "Couldn't get subdomain ID from Digital Ocean."
fi
curl --silent --request PUT --header "Content-Type: application/json" --header "Authorization: Bearer ${apiKey}" -d "{\"data\":\"${localIp}\"}" "https://api.digitalocean.com/v2/domains/${domain}/records/${subdomainId}" > /dev/null
if [ $? -ne 0 ]; then
die "Couldn't connect to Digital Ocean API."
fi
fi