Skip to content

Instantly share code, notes, and snippets.

@suvash
Last active May 1, 2019 00:31
Show Gist options
  • Save suvash/a42c8c02b3e703a956889a4d450118b8 to your computer and use it in GitHub Desktop.
Save suvash/a42c8c02b3e703a956889a4d450118b8 to your computer and use it in GitHub Desktop.
Cloudflare DNS record update via bash (for DDNS like behaviour)
#!/usr/bin/env bash
DDNS_DIR='/tmp/cf_ddns'
PREVIOUS_IP_FILE="$DDNS_DIR/dynamic_ip.txt"
CF_REQUEST_RESPONSE_FILE="$DDNS_DIR/cf_response.json"
mkdir -p "$DDNS_DIR"
[ ! -f "$PREVIOUS_IP_FILE" ] && touch "$PREVIOUS_IP_FILE"
# NEW_IP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
NEW_IP="$(curl -s checkip.amazonaws.com)"
PREVIOUS_IP="$(cat $PREVIOUS_IP_FILE)"
CF_EMAIL="[email protected]" # Email address for CF account
CF_ZONE_ID="the-zone-id-for-your-domain" # The Zone ID for your domain/zone
CF_API_KEY="your-cloudflare-global-api-key" # Your CF Global API key - careful with this
CF_DNS_RECORD_ID="the-record-id-for-your-entry" # Check CF api to get this
CF_DNS_RECORD_TYPE="the-record-type-for-your-entry" # A / CNAME etc.
CF_DNS_RECORD_NAME="somedomain.here" # The domain/zone name
if [ "$NEW_IP" = "$PREVIOUS_IP" ]; then
echo "IP address NOT changed : $NEW_IP"
else
echo "IP address has changed : $NEW_IP"
echo "Updating DNS record..."
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/dns_records/$CF_DNS_RECORD_ID" \
-H "X-Auth-Email: $CF_EMAIL" \
-H "X-Auth-Key: $CF_API_KEY" \
-H "Content-Type: application/json" \
--data "{\"type\":\"$CF_DNS_RECORD_TYPE\",\"name\":\"$CF_DNS_RECORD_NAME\",\"content\":\"$NEW_IP\"}" \
> "$CF_REQUEST_RESPONSE_FILE"
if grep --quiet '"success":true' "$CF_REQUEST_RESPONSE_FILE"; then
echo "Sucessfully updated DNS record..."
echo "$NEW_IP" > "$PREVIOUS_IP_FILE"
else
echo "Could not update DNS record..."
cat "$CF_REQUEST_RESPONSE_FILE"
exit 1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment