Created
June 22, 2020 16:37
-
-
Save lytedev/a2091738d1716fcc49a02e3e6cd290d4 to your computer and use it in GitHub Desktop.
Netlify DDNS
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 | |
# options | |
TTL="120" | |
SUBDOMAINS=(host1 host2 host3) | |
ACCESS_TOKEN="???" | |
DOMAIN="lyte.dev" | |
# constants | |
DNS_ZONE="$(<<< "$DOMAIN" sd "\." "_")" | |
API="https://api.netlify.com/api/v1" | |
URL="$API/dns_zones/$DNS_ZONE/dns_records?access_token=$ACCESS_TOKEN" | |
# setup | |
CURL_FLAGS="-sL" | |
curl="curl $CURL_FLAGS" | |
# fetch IP addresses | |
MY_IPV4="$($curl -4 ifconfig.io)" | |
MY_IPV6="$($curl -6 ifconfig.io)" | |
# fetch current netlify DNS state | |
CURRENT_DNS_JSON="$(curl -sL "$URL" | jq -r 'map(select(.type == "A" or .type == "AAAA"))')" | |
jsq() { | |
<<< "$CURRENT_DNS_JSON" jq "$@" | |
} | |
delete_netlify_dns_record_by_subdomain_if_exists() { | |
SUBDOMAIN="$1"; shift | |
if jsq -e "map(select(.hostname == \"$SUBDOMAIN.$DOMAIN\"))[0]" > /dev/null; then | |
RECORD_ID="$(jsq -r "map(select(.hostname == \"$SUBDOMAIN.$DOMAIN\"))[0].id")" | |
$curl -X DELETE "$API/dns_zones/$DNS_ZONE/dns_records/$RECORD_ID?access_token=$ACCESS_TOKEN" > /dev/null | |
fi | |
} | |
create_netlify_dns_record() { | |
SUBDOMAIN="$1"; shift | |
PAYLOAD="$(jq -n -r \ | |
--arg type "A" \ | |
--arg name "$SUBDOMAIN" \ | |
--arg val "$MY_IPV4" \ | |
--arg ttl "$TTL" \ | |
'{type:$type,hostname:$name,value:$val,ttl:$ttl}')" | |
<<< "$PAYLOAD" $curl -d @- -H 'content-type:application/json' "$API/dns_zones/$DNS_ZONE/dns_records?access_token=$ACCESS_TOKEN" > /dev/null | |
} | |
setup_netlify_dns_record() { | |
SUBDOMAIN="$1"; shift | |
echo "Setting up $SUBDOMAIN.$DOMAIN" | |
delete_netlify_dns_record_by_subdomain_if_exists "$SUBDOMAIN" | |
create_netlify_dns_record "$SUBDOMAIN" | |
} | |
for s in "${SUBDOMAINS[@]}"; do | |
setup_netlify_dns_record "$s" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment