Companion script for cloudflare-ddns

Unfortunatelly cloudflare-ddns package in the debian repo can not handle more than 1 domain to update its DNS records. The following script will edit the config.ini file used for cloudflare-ddns to add the domain and the api tocken necessary for making updates. It will cycle all domains included in the array DOMAINS.

#!/bin/bash
# Path of file /etc/cloudflare-ddns/domains_cycling.sh

# Define the path to your config file and the counter file
CONFIG_FILE="/etc/cloudflare-ddns/config.ini"
COUNTER_FILE="/etc/cloudflare-ddns/domain_counter"

# List of domains and API keys
DOMAINS=(
 "site1.com|l2_kx_xaSiw_EXAMPLE_API_KEY_7lNBvJvlKzchx"
 "site2.com|l2_kx_xaSiw_EXAMPLE_API_KEY_7lNBvJvlKzchx"
 "site3.com|l2_kx_xaSiw_EXAMPLE_API_KEY_7lNBvJvlKzchx"
)

# Get the total number of domains
NUM_DOMAINS=${#DOMAINS[@]}

# Ensure there are domains in the list
if [ $NUM_DOMAINS -eq 0 ]; then
 echo "Error: No domains found in the list. Exiting script."
 exit 1
fi

# Read the current counter value from the counter file
if [ -f "$COUNTER_FILE" ]; then
 COUNTER=$(cat "$COUNTER_FILE")
else
 COUNTER=0  # If no counter file exists, start from the first domain
fi

# Make sure the counter is within the valid range
if [ $COUNTER -ge $NUM_DOMAINS ]; then
 COUNTER=0  # Reset the counter if it exceeds the number of domains
fi

# Get the current domain and API key based on the counter
DOMAIN_API_KEY=${DOMAINS[$COUNTER]}
DOMAIN=$(echo $DOMAIN_API_KEY | cut -d'|' -f1)
API_KEY=$(echo $DOMAIN_API_KEY | cut -d'|' -f2)

# Update the config file with the new domain and API key
sed -i "s/^api_token = .*/api_token = $API_KEY/" "$CONFIG_FILE"
sed -i "s/^record_name = .*/record_name = $DOMAIN/" "$CONFIG_FILE"

# Increment the counter and save it back to the counter file
COUNTER=$(( (COUNTER + 1) % NUM_DOMAINS ))
echo $COUNTER > "$COUNTER_FILE"  # Save the updated counter value to the file

# Exit the script
echo "Updated config file with domain: $DOMAIN and API key: $API_KEY"
echo "Exiting after update."
exit 0

Additionally, a cron job needs to be setup to run the script every 5 mins. Add the following line at the end of the file.

sudo crontab -e

*/5 * * * * /bin/bash /etc/cloudflare-ddns/domains_cycling.sh

Cloudflare-ddns attempts and DNS record update every 5 mins and as domain_cycling.sh script changes the information in the config.ini file, it will always check a new domain. This limits the response time for each new domain is added in case of a ip change to 10 mins for 2 domains, 15 mins for 3 and so on.