Created
April 25, 2022 01:49
-
-
Save joeltg/dbe545e2e13aeec7804faae87651f041 to your computer and use it in GitHub Desktop.
Cloudflar Dynamic DNS 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/sh | |
zone_identifier="" | |
record_name="" | |
auth_token="" | |
get_response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records?name=${record_name}&type=A" -H "Authorization: Bearer ${auth_token}" -H "Accept: application/json") | |
get_success=$(echo ${get_response} | jq .success) | |
if [ "${get_success}" != "true" ]; then | |
>&2 echo "API GET failed, cannot fetch DNS record." | |
exit 1 | |
fi | |
count=$(echo ${get_response} | jq .result_info.count) | |
if [ "${count}" != "1" ]; then | |
>&2 echo "No existing A record." | |
fi | |
record=$(echo ${get_response} | jq .result[0]) | |
record_id=$(echo ${record} | jq -r .id) | |
record_content=$(echo ${record} | jq -r .content) | |
# Check for current external network IP | |
ip=$(curl -s https://icanhazip.com/) | |
if [ "${ip}" != "" ]; then | |
echo "Fetched current external network IP: ${ip}" | |
else | |
>&2 echo "Network error, cannot fetch external network IP." | |
fi | |
if [ "${ip}" = "${record_content}" ]; then | |
echo "Update for A record ${record_name} cancelled; IP has not changed." | |
exit 0 | |
else | |
echo "Different IP addresses detected, synchronizing..." | |
fi | |
data="{\"content\":\"${ip}\"}" | |
patch_response=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records/${record_id}" -H "Authorization: Bearer ${auth_token}" -H "Content-Type: application/json" --data ${data}) | |
patch_success=$(echo ${patch_response} | jq .success) | |
if [ "${patch_success}" = "true" ]; then | |
echo "Successfully updated A record for ${record_name}.\n - Old value: ${record_content}\n + New value: ${ip}" | |
exit 0 | |
else | |
>&2 echo "APT PATCH failed, cannot update DNS record." | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment