24 Apr, 2021
In this post I'll share a script I use for updating my DNS entries with Gandi every time the public IP of my network changes.
To use it you'll need Gandi.net DNS entries, and an API key.
You can generate or regenerate your API key from your account security page:
Now save the following script somewhere like:
/apps/gandi-update-ip.sh
The script looks like this:
#!/bin/sh
set -e
IP_FILE=/apps/ip
# Requires these environment variables set:
# GANDI_API_KEY
if [ "$GANDI_API_KEY" = "" ]; then
echo "Error: No GANDI_API_KEY environment variable set"
echo "Usage: GANDI_API_KEY=... $0 IP HOST"
exit 1
fi
if [ "$#" -ne 0 ]; then
echo "Error: No arguments expected"
echo "Usage: GANDI_API_KEY=... $0"
exit 1
fi
if [ ! -f "$IP_FILE" ]; then
touch "$IP_FILE"
fi
IP=`wget -q -O- http://whatismyip.akamai.com`
OLD_IP=`cat "${IP_FILE}"`
date
if [ "${IP}" != "${OLD_IP}" ]; then
echo "Setting IP to: ${IP}"
# jimmyg.org
wget -q -O- --method PUT \
--header "Content-Type: application/json" \
--header "X-Api-Key: ${GANDI_API_KEY}" \
--body-data "{\"rrset_ttl\": 311, \"rrset_values\": [\"${IP}\"]}" \
'https://dns.api.gandi.net/api/v5/domains/example.com/records/@/A'
wget -q -O- --method PUT \
--header "Content-Type: application/json" \
--header "X-Api-Key: ${GANDI_API_KEY}" \
--body-data "{\"rrset_ttl\": 311, \"rrset_values\": [\"${IP}\"]}" \
'https://dns.api.gandi.net/api/v5/domains/example.com/records/www/A'
echo "${IP}" > "${IP_FILE}"
echo
echo "Done."
else
echo "Nothing to do."
fi
echo
To find your public IP, this script uses http://whatismyip.akamai.com but you can find your public IP any way you like. In the past I've got the IP directly from my 4G router for example.
Then set a cron job for every hour (or more frequent if you like) using sudo crontab -e
and use your API key where it says XXX
below:
7 * * * * GANDI_API_KEY=XXX /apps/gandi-update-ip.sh >> /apps/iplog 2>> /apps/iplog
If your IP address changes, the script will update the DNS entries and log to /apps/iplog
. If the IP is the same, the updating will be skipped.
In the past I used curl
and the Gandi API zone endpoint which meant the command I used to update the DNS looked like this:
curl -X PUT -H "Content-Type: application/json" \
-H "X-Api-Key: ${APIKEY}" \
-d "{\"rrset_ttl\": 300, \"rrset_values\": [\"${IP}\"]}" \
https://dns.api.gandi.net/api/v5/zones/xxx/records/wiki/A
I think this is much harder to follow though, because you need the ID of the zone from Gandi, not the domain name.
Be the first to comment.
Copyright James Gardner 1996-2020 All Rights Reserved. Admin.