Skip to content

Instantly share code, notes, and snippets.

@mukhortov
Last active May 18, 2021 10:51
Show Gist options
  • Save mukhortov/a65605b4db977f5fdeb2cbfdebd9c422 to your computer and use it in GitHub Desktop.
Save mukhortov/a65605b4db977f5fdeb2cbfdebd9c422 to your computer and use it in GitHub Desktop.
Automatically update Cloudflare DNS record when the server IP has changed.
#!/bin/bash
#
# Automatically update Cloudflare DNS record when the server IP has changed.
#
# 1. Update params below
#
# 2. Add execute permissions:
# chmod +x ./update-dns-record.sh
#
# 3. To run every hour with cron edit crontab file:
# crontab -e
#
# 4. Add folowing record to the opened crontab file (change the path to the file):
# 0 * * * * /absolute/path/to/update-dns-record.sh
#
# 5. Pres ':' + 'w' + 'q' to save and quit
#
# API Documentation
# https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
#
# Params
domain="yourdomain.com"
zoneID="your_cloudflare_zone_id_goes_here"
dnsRecordID="your_cloudflare_dns_record_id_goes_here"
apiToken="your_cloudflare_api_token_goes_here"
# Get the current public IP
currentIP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
# Get the current DNS IP
dnsIP="$(dig +short ${domain})"
echo "DNS IP: ${dnsIP}"
echo "Current IP: ${currentIP}"
if [[ $dnsIP != $currentIP ]]; then
# Update DNS record
echo 'Updating...'
success=`curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/${zoneID}/dns_records/${dnsRecordID}" \
-H "Authorization: Bearer ${apiToken}" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"${domain}\",\"content\":\"${currentIP}\",\"ttl\":1,\"proxied\":false}" \
| jq -r '.success'`
if [[ $success == true ]]; then
echo "The DNS record has been updated. The new IP is: ${currentIP}"
else
echo 'Update failed'
fi
else
# Don't update
echo "The DNS record is already up-to-date: ${dnsIP}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment