Last active
October 30, 2019 18:12
-
-
Save gadelkareem/5603f76b817a7d6396350f1fb7180f6c to your computer and use it in GitHub Desktop.
Update cloudflare DNS https://gadelkareem.com/2019/06/11/update-cloudflare-dns-using-bash/
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
#!/usr/bin/env bash | |
set -euo pipefail | |
DOMAIN=$1 | |
SUB_DOMAIN="${2}.${DOMAIN}" | |
CF_ID=$3 | |
CF_KEY=$4 | |
IP= | |
if [ -n "${5+x}" ]; then | |
IP=$5 | |
else | |
IP=$(curl -s http://ipv4.icanhazip.com) | |
fi | |
echo "Updating DNS for ${SUB_DOMAIN}..." | |
ZONE=$(curl -sLX GET "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}&status=active" \ | |
-H "X-Auth-Email: ${CF_ID}" \ | |
-H "X-Auth-Key: ${CF_KEY}" \ | |
-H "Content-Type: application/json" | jq -r .result[0].id) | |
RECORD=$(curl -sLX GET "https://api.cloudflare.com/client/v4/zones/${ZONE}/dns_records?name=${SUB_DOMAIN}" \ | |
-H "X-Auth-Email: ${CF_ID}" \ | |
-H "X-Auth-Key: ${CF_KEY}" \ | |
-H "Content-Type: application/json" | jq -r .result[0].id) | |
echo "Got record id ${RECORD}" | |
if [[ "${#RECORD}" -le 10 ]]; then | |
RECORD=$(curl -sLX POST "https://api.cloudflare.com/client/v4/zones/${ZONE}/dns_records" \ | |
-H "X-Auth-Email: ${CF_ID}" \ | |
-H "X-Auth-Key: ${CF_KEY}" \ | |
-H "Content-Type: application/json" \ | |
--data '{"type":"A","name":"'${SUB_DOMAIN}'","content":"'${IP}'","ttl":120,"proxied":false}' | jq -r .result.id) | |
echo "Created record id ${RECORD}" | |
fi | |
RESULT=$(curl -sLX PUT "https://api.cloudflare.com/client/v4/zones/${ZONE}/dns_records/${RECORD}" \ | |
-H "X-Auth-Email: ${CF_ID}" \ | |
-H "X-Auth-Key: ${CF_KEY}" \ | |
-H "Content-Type: application/json" \ | |
--data '{"type":"A","name":"'${SUB_DOMAIN}'","content":"'${IP}'","ttl":120,"proxied":false}') | |
echo "${RESULT}" | |
if [[ "${RESULT}" != *"success\":true"* ]] && [[ "${RESULT}" != *"A record with those settings already exists."* ]] ; then | |
exit 1 | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment