Last active
April 23, 2020 16:34
-
-
Save braddevans/ef19871ac06db6f507a971c12d1df01a to your computer and use it in GitHub Desktop.
update to the cloudflare dns updater
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/bash | |
while getopts z:e:a:t:n:p: option | |
do | |
case "${option}" | |
in | |
z) ZONEID=${OPTARG};; | |
a) APITOKEN=${OPTARG};; | |
t) ZONETYPE=${OPTARG};; | |
n) RECORD_NAME=${OPTARG};; | |
e) EMAIL=${OPTARG};; | |
p) PROXIED=${OPTARG};; | |
esac | |
done | |
cf_api_url="https://api.cloudflare.com/client/v4" | |
get_record_id () { | |
local records | |
local records_count | |
records=`curl -s -X GET "${cf_api_url}/zones/${ZONEID}/dns_records?name=${RECORD_NAME}&type=A" -H "X-Auth-Email: ${EMAIL}" -H "Authorization: Bearer ${APITOKEN}" -H "Content-Type: application/json"` | |
if [ ! "${records}" ]; then | |
echo "Request to API failed during record lookup." | |
exit 1 | |
fi | |
if [ -n "${records##*\"success\":true*}" ]; then | |
echo "Failed to lookup DNS record ID. Check record name or specify an ID." | |
echo "${records}" | |
exit 1 | |
fi | |
records=`echo "${records}" | grep -Po '(?<="id":")[^"]*'` | |
records_count=`echo "${records}" | wc -w` | |
if [ $records_count -gt 1 ]; then | |
echo "Multiple DNS A records match ${record_name}. Please specify a record ID." | |
exit 1 | |
fi | |
recordID="${records}" | |
return 0 | |
} | |
do_A_record_update () { | |
# Perform record update | |
IP=`curl -s https://ifconfig.io/ip` | |
api_dns_update=`curl -s -X PUT "${cf_api_url}/zones/${ZONEID}/dns_records/${recordID}" -H "X-Auth-Email: ${EMAIL}" -H "Authorization: Bearer ${APITOKEN}" -H "Content-Type: application/json" --data "{\"type\": \"${ZONETYPE}\", \"name\":\"${RECORD_NAME}\", \"content\":\"${IP}\", \"ttl\":120, \"proxied\": ${PROXIED}}" | jq '.success'` | |
if [ ! $api_dns_update ]; then | |
echo "Record update failed." | |
echo `curl -s -X PUT "${cf_api_url}/zones/${ZONEID}/dns_records/${recordID}" -H "X-Auth-Email: ${EMAIL}" -H "Authorization: Bearer ${APITOKEN}" -H "Content-Type: application/json" --data "{\"type\": \"${ZONETYPE}\", \"name\":\"${RECORD_NAME}\", \"content\":\"${IP}\", \"ttl\":120, \"proxied\": ${PROXIED}}"` | |
exit 1 | |
fi | |
if [ $api_dns_update ]; then | |
echo "Record update succeeded." | |
exit 1 | |
fi | |
return 0 | |
} | |
get_record_id | |
echo "API_TOKEN: ${APITOKEN}" | |
echo "Zone_ID: ${ZONEID}" | |
echo "Record_ID: ${recordID}" | |
echo "RECORD_NAME: ${RECORD_NAME}" | |
echo "RECORD_UPDATE_TYPE: ${ZONETYPE}" | |
do_A_record_update |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: