-
-
Save arnissolle/b23a873fbaec309b252fb44068bd5216 to your computer and use it in GitHub Desktop.
A bash script to update a Cloudflare DNS A record with the external IP of the source machine
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 sh | |
| # A bash script to update a Cloudflare DNS A record with the external IP of the source machine | |
| # Used to provide DDNS service for my home | |
| # Needs the DNS record pre-creating on Cloudflare | |
| # Proxy - uncomment and provide details if using a proxy | |
| #export https_proxy=http://<proxyuser>:<proxypassword>@<proxyip>:<proxyport> | |
| # Cloudflare zone is the zone which holds the record | |
| zone=example.com | |
| # dnsrecords are the A records which will be updated | |
| dnsrecords=(*.example.com www.example.com admin.example.com) | |
| # Cloudflare authentication details | |
| cloudflare_auth_token=1234567893feefc5f0q5000bfo0c38d90bbeb | |
| # Get the current external IP address | |
| ip=$(curl -s -X GET https://checkip.amazonaws.com) | |
| echo "Current external IP is $ip" | |
| # Loop over DNS records | |
| for dnsrecord in ${dnsrecords[@]} | |
| do | |
| # check is host need to update | |
| if host $dnsrecord 1.1.1.1 | grep "has address" | grep "$ip"; then | |
| echo "$dnsrecord is currently set to $ip; no changes needed" | |
| continue | |
| else | |
| echo "Try to refresh $dnsrecord A record with $ip" | |
| fi | |
| # if here, the dns record needs updating | |
| # get the dns zone id | |
| dnszoneid=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone" \ | |
| -H "Authorization: Bearer $cloudflare_auth_token" \ | |
| -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id') | |
| echo "DNSzoneid for $zone is $dnszoneid" | |
| # get the dns record id | |
| dnsrecordid=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$dnszoneid/dns_records?type=A&name=$dnsrecord" \ | |
| -H "Authorization: Bearer $cloudflare_auth_token" \ | |
| -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id') | |
| echo "DNSrecordid for $dnsrecord is $dnsrecordid" | |
| # update the record | |
| curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$dnszoneid/dns_records/$dnsrecordid" \ | |
| -H "Authorization: Bearer $cloudflare_auth_token" \ | |
| -H "Content-Type: application/json" \ | |
| --data "{\"type\":\"A\",\"name\":\"$dnsrecord\",\"content\":\"$ip\",\"ttl\":1,\"proxied\":false}" | jq | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment