Skip to content

Instantly share code, notes, and snippets.

@jess-sol
Created March 17, 2021 17:14
Show Gist options
  • Select an option

  • Save jess-sol/3c5c4ca665b32655c4b4b0d7065c579e to your computer and use it in GitHub Desktop.

Select an option

Save jess-sol/3c5c4ca665b32655c4b4b0d7065c579e to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
ACCESS_TOKEN=$(< token)
function ddns {
local record="domain.tld"
local domain="exiting.a.record"
ip="$(curl -s http://checkip.amazonaws.com/)"
record_id="$(get_id_for_name "$record" "$domain")"
echo "Setting '$record' ($record_id) in $domain to $ip"
response="$(set_dns_record_data "$domain" "$record_id" "$ip")"
jq -M . <<< "$response"
[[ "$(jq -r .domain_record.data <<< "$response")" == "$ip" ]]
}
function fetch_url {
local url="$1"
curl \
--silent \
-X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
"$url"
}
function post_url {
local url="$1"
local verb="$2"
local data="$3"
curl \
--silent \
-X "$verb" \
--data "$data" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
"$url"
}
# Search records for name
function get_id_for_name {
local record="$1"
local domain="$2"
response="$(fetch_url "https://api.digitalocean.com/v2/domains/$domain/records")"
while true; do
result=$(jq --arg record "$record" '.domain_records[] | select(.name == $record)' <<< "$response")
# Exit
if [[ -n "$result" ]]; then
jq -r '.id' <<< "$result"
return 0
fi
# Go next if possible
next_url="$(echo "$response" | jq -r '.links.pages.next // ""')"
if [[ -n "$next_url" ]]; then
response="$(fetch_url "$next_url")"
continue
fi
# Hasn't been found and can't go next
return 1
done
}
function set_dns_record_data {
local domain="$1"
local record_id="$2"
local data="$3"
json_data="$(jq -n --arg data "$data" '{"data": $data}')"
post_url "https://api.digitalocean.com/v2/domains/$domain/records/$record_id" "PUT" "$json_data"
}
ddns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment