This Python script checks if your public IP address has changed and updates the corresponding A records in Cloudflare DNS if necessary.
The script is designed for users who manage their own hosting servers and use Cloudflare for DNS management. It ensures that the DNS records in Cloudflare are always up-to-date with the current public IP address, which is particularly useful for users without a static IP.
- Python 3.x
requests
librarypython-dotenv
library
First, make sure you have Python 3.x installed. Then, install the required Python libraries using pip:
pip install requests python-dotenv
- Log in your Cloudflare account and go to "My Profile" -> "API Tokens"
- View your "Global API Key" and save it for later
Get your zones using Cloudflare API
curl -X GET "https://api.cloudflare.com/client/v4/zones" \
-H "Content-Type: application/json" \
-H "X-Auth-Email: <your-email-address>" \
-H "X-Auth-Key: <your-global-api-key>"
# or using API Token
curl -X GET "https://api.cloudflare.com/client/v4/zones" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-api-token>"
Get dns records of a zone using Cloudflare API
curl -X GET "https://api.cloudflare.com/client/v4/zones/<zone-id>/dns_records" \
-H "Content-Type: application/json" \
-H "X-Auth-Email: <your-email-address>" \
-H "X-Auth-Key: <your-global-api-key>"
# or using API Token
curl -X GET "https://api.cloudflare.com/client/v4/zones/<zone-id>/dns_records" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-api-token>"
Create a .env file in the same directory as your script and add your Cloudflare API credentials and DNS records information. The .env file should look like this:
CLOUDFLARE_EMAIL=[email protected]
# May contain Cloudflare API Key or API Token
CLOUDFLARE_API_KEY=your-api-key
ZONE_ID=["your-zone-id-d41f54"]
DNS_RECORDS_d41f54=[("dns-record-id-1", "example.com"), ("dns-record-id-2", "sub.example.com")]
ZONE_ID
is an array of the zones you want to work with.You need to add an entry
DNS_RECORDS_[...]
in the .env for each zone and append the last 6 char of the zone id.If you used an API Token, you can omit
CLOUDFLARE_EMAIL
For more information concerning the cloudflare API please refer to the Cloudflare API documentation
Run the script using Python:
python update_dns.py
You can automate this script to run at regular intervals using a task scheduler like cron on Linux or Task Scheduler on Windows.
Exemple to run the script every 5 minutes using CRON :
*/5 * * * * /usr/bin/python3 /path/to/your/script/update_dns.py >> /path/to/your/logfile.log 2>&1
This project is licensed under the MIT License.