GadElKareem

Update cloudflare DNS using bash

Usage:

./cloudflare-dns.sh example.com sub-domain cloudflare_email@example.com cloudflare_token

#!/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

fork it