Skip to content

Instantly share code, notes, and snippets.

@jkpark
Created March 14, 2019 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkpark/c2cfbb84728feb05c20c5d3950e10f20 to your computer and use it in GitHub Desktop.
Save jkpark/c2cfbb84728feb05c20c5d3950e10f20 to your computer and use it in GitHub Desktop.
update ddns for cloudflare
#!/bin/bash
# 2019-03-07 | jkpark | Created
# Account and Domain
EMAIL=email@address.com
KEY=df8e92___your_global_api_key___bd5526
DOMAIN=exsample.com
A_RECORD_LIST=exsample.com,cloud.exsample.com
# Reference
IP=$(curl -s http://ipv4.icanhazip.com)
PREV_IP_FILE="/var/local/previous_ip"
LOGFILE="/var/log/ddns-cloudflare.log"
# Logger
log() {
if [ "$1" ]; then
echo -e "$(date +%Y.%m.%d_%H.%M.%S) $1" >> $LOGFILE
echo -e "$(date +%Y.%m.%d_%H.%M.%S) $1"
fi
}
######
if [[ $1 == "-f" ]]; then
echo "Force update..."
elif [ -f "$PREV_IP_FILE" ]; then
PREV_IP=$(cat -s $PREV_IP_FILE)
if [ "$IP" == "$PREV_IP" ]; then exit 0; fi
fi
echo $IP > $PREV_IP_FILE
V4ZONE="https://api.cloudflare.com/client/v4/zones"
HEADERS="-HX-Auth-Email:$EMAIL -HX-Auth-Key:$KEY -HContent-Type:application/json"
ZONE_ID=$(curl -s -X GET "$V4ZONE?name=$DOMAIN" $HEADERS | jq -r .result[0].id )
update_record() {
RECORD_ID=$(curl -s -X GET "$V4ZONE/$ZONE_ID/dns_records?type=A&name=$1" $HEADERS | jq -r .result[0].id)
if [ "$RECORD_ID" == "null" ]; then
log "Record update failed. Record '$1' does not exist."
log "Creating a new A record : $1"
DATA="--data {\"type\":\"A\",\"name\":\"$1\",\"content\":\"$IP\"}"
result=$(curl -s -X POST "$V4ZONE/$ZONE_ID/dns_records" $HEADERS $DATA | jq .success)
if [ "$result" == "true" ]; then
log "Record $1 is created."
fi
return 0;
fi
DATA="--data {\"type\":\"A\",\"name\":\"$1\",\"content\":\"$IP\"}"
result=$(curl -s -X PUT "$V4ZONE/$ZONE_ID/dns_records/$RECORD_ID" $HEADERS $DATA | jq .success)
if [ "$result" == "true" ]; then
log "Record $1 is updated."
fi
}
_l=$(echo $A_RECORD_LIST | tr "," "\n")
for a in $_l; do update_record $a; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment