Created
November 16, 2022 18:40
-
-
Save rajrajhans/d8827b560cc317cf6e95bdb3647b0162 to your computer and use it in GitHub Desktop.
Simple shell script to update specific CloudFlare DNS record with current ip. Useful when you do not have a static IP address, and are hosting your own servers.
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
| #!/bin/bash | |
| # run this script as a CRON job! | |
| # get the current public ip address | |
| printf "\n" | |
| logger -s "Getting the current public IP address..." | |
| current_ip=`curl -s ipinfo.io/ip` | |
| update_dns_record(){ | |
| # function to update the dns record in cloudflare | |
| curl -s --request PUT \ | |
| --url https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/dns_records/$CLOUDFLARE_RECORD_ID \ | |
| --header 'Content-Type: application/json' \ | |
| --header "X-Auth-Email: $CLOUDFLARE_EMAIL_ID" \ | |
| --header "X-Auth-Key: $CLOUDFLARE_AUTH_KEY" \ | |
| --data "{ | |
| \"content\": \"$current_ip\", | |
| \"type\": \"A\", | |
| \"name\": \"$CLOUDFLARE_RECORD_NAME\", | |
| \"ttl\": \"$CLOUDFLARE_RECORD_TTL\", | |
| \"proxied\": $CLOUDFLARE_PROXIED_TRUE_OR_FALSE | |
| }" | |
| logger -s "done updating the dns record" | |
| } | |
| # check if `ip.log` file exists (we store the last ip address in this file) | |
| if [ -e ip.log ] | |
| then | |
| # it exists, so read the last ip address from it | |
| last_ip=`cat ip.log` | |
| # compare the current ip address with the last ip address | |
| if [ "$current_ip" != "$last_ip" ] | |
| then | |
| printf "\n" | |
| logger -s "it has changed, updating dns record..." | |
| # they are different, so update the DNS record | |
| update_dns_record | |
| # save the current ip address to the `ip.log` file | |
| echo $current_ip > ip.log | |
| exit 0 | |
| else | |
| logger -s "ip address has not changed. exiting" | |
| fi | |
| else | |
| logger -s "no ip.log file found, creating one" | |
| echo $current_ip > ip.log | |
| update_dns_record | |
| exit 0 | |
| fi | |
| # save the current ip address to the `ip.log` file | |
| echo $current_ip > ip.log | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment