homelab-automation/Bash/cloudflare-dns.sh
Benjamin Hays d755bad314
Some checks failed
Ansible Lint / build (push) Failing after 1m6s
Add Dynamic DNS and Heartbeat Playbook
2024-10-11 19:06:13 -04:00

70 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
ttl="600"
proxied="false"
zoneid=''
cloudflare_zone_api_token=''
dns_record=''
REIP='^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])$'
if which ip >/dev/null; then
interface=$(ip route get 1.1.1.1 | awk '/dev/ { print $5 }')
ip=$(ip -o -4 addr show ${interface} scope global | awk '{print $4;}' | cut -d/ -f 1)
else
echo "Error! 'ip' command not found. Please install iproute2."
exit 1
fi
if [ -z "$ip" ]; then
echo "Error! Can't read ip from ${interface}"
exit 1
fi
echo "==> Internal ${interface} IP is: $ip"
IFS=',' read -d '' -ra dns_records <<<"$dns_record,"
unset 'dns_records[${#dns_records[@]}-1]'
declare -a dns_records
for record in "${dns_records[@]}"; do
if [ "${proxied}" == "false" ]; then
if which nslookup >/dev/null; then
dns_record_ip=$(nslookup ${record} 1.1.1.1 | awk '/Address/ { print $2 }' | sed -n '2p')
else
dns_record_ip=$(host -t A ${record} 1.1.1.1 | awk '/has address/ { print $4 }' | sed -n '1p')
fi
if [ -z "$dns_record_ip" ]; then
echo "Error! Can't resolve the ${record} via DNS"
exit 1
fi
is_proxed="${proxied}"
fi
cloudflare_record_info=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records?type=A&name=$record" \
-H "Authorization: Bearer $cloudflare_zone_api_token" \
-H "Content-Type: application/json")
if [[ ${cloudflare_record_info} == *"\"success\":false"* ]]; then
echo ${cloudflare_record_info}
echo "Error! Can't get ${record} record information from Cloudflare API"
exit 1
fi
cloudflare_dns_record_id=$(echo ${cloudflare_record_info} | grep -o '"id":"[^"]*' | cut -d'"' -f4)
update_dns_record=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records/$cloudflare_dns_record_id" \
-H "Authorization: Bearer $cloudflare_zone_api_token" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$record\",\"content\":\"$ip\",\"ttl\":$ttl,\"proxied\":$proxied}")
if [[ ${update_dns_record} == *"\"success\":false"* ]]; then
echo ${update_dns_record}
echo "Error! Update failed"
exit 1
fi
echo "==> Success!"
echo "==> $record DNS Record updated to: $ip, ttl: $ttl, proxied: $proxied"
done