Updating CloudFlare API with your latest Home IP

Go to this article instead https://ades-blog.tiempo.llc/updating-cloudflare-with-your-home-ip-using-python/

There are multiple scenarios where you would like to have a domain name pointing to your home IP address. One method is to use a service like DuckDNS but there are several Dynamic DNS services you could use. Most Dynamic DNS services only allow you to update the C Name (e.g. <your-domain>.example.com) but using the CloudFlare API lets you update your A or C Name records.

You can use this API to update your DNS records with your latest home IP address. Here are the steps to create a Python script that updates your Cloudflare DNS records with your dynamic IP address. If you wish to do this without using the Python CloudFlare library, I’ve created a separate post here Updating CloudFlare with your Home IP using Python

  1. First, you need to obtain your Cloudflare API key. You can find your API key in your Cloudflare account settings.
  2. Next, you need to install the cloudflare Python package. You can install it using pip by running the following command: pip install cloudflare.
  3. Once you’ve installed the cloudflare package, you can use the following Python script to update your DNS records:
from CloudFlare import CloudFlare
import requests

def main():
    # Set your domain name and record name
    zone_name = 'example.com'
    record_name = 'home.example.com'
    # Set your Cloudflare API key and email
    email='[email protected]'
    token='your-api-key'

    cf = CloudFlare(email=email,token=token)

    # Get your current public IP address
    ip = requests.get('https://api.ipify.org').text
    
    # Update your DNS record with your current IP address
    dns_record = cf.zones.dns_records.get(cf.zones.get(params={'name': zone_name})[0]['id'], params={'name': record_name})
    dns_record['content'] = ip
    cf.zones.dns_records.put(cf.zones.get(params={'name': zone_name})[0]['id'], dns_record['id'], data=dns_record)

if __name__ == '__main__':
    main()

Replace [email protected] and your-api-key with your Cloudflare email and API key, respectively. Replace example.com with your domain name and home.example.com with your record name. This script will update your DNS record with your current public IP address.

You can run this script periodically using a cron job or a systemd timer to keep your DNS records up-to-date.

I’ve also included this script in my GitHub account so you can simply run a git clone of https://github.com/sigmaenigma/CloudFlare.git

A more comprehensive version is below which includes code to check if the IP had changed and to only update if there was a change:

from CloudFlare import CloudFlare
import requests
import json
import ipaddress # import the ipaddress module

""" 
Update your DNS record in CloudFlare with your Home IP  
"""

def get_config():
    try:
        # Open the config.json file in read mode
        with open('config.json', 'r') as f:
            
            # Load the JSON data from the file
            config = json.load(f)

            # Return the values as a dictionary
            return config
    except Exception as e:
        print(f'An issue occured trying to open the configuration file: {e}')

def main():
    try:
        # Call the get_config function and assign the values to variables
        config = get_config()
        zone_name = config['zone_name']
        record_name = config['record_name']
        email = config['email']
        token = config['token']

        cf = CloudFlare(email=email,token=token)

        # Get your current public IP address
        ip = requests.get('https://api.ipify.org').text
        
        # Get your old IP address from the DNS record
        dns_record = cf.zones.dns_records.get(cf.zones.get(params={'name': zone_name})[0]['id'], params={'name': record_name})
        old_ip = dns_record['content']

        # Convert the IP addresses to ipaddress objects
        ip = ipaddress.ip_address(ip)
        old_ip = ipaddress.ip_address(old_ip)

        # Check if the IP addresses are different
        if ip != old_ip:
            # Update your DNS record with your current IP address
            dns_record['content'] = str(ip) # convert the ip object to a string
            cf.zones.dns_records.put(cf.zones.get(params={'name': zone_name})[0]['id'], dns_record['id'], data=dns_record)
            print(f'IP address changed from {old_ip} to {ip}. DNS record updated.')
        else:
            # No need to update the DNS record
            print(f'IP address is still {ip}. No change needed.')
        return True
    except Exception as e:
        print(f'An issue occured trying to update the CloudFlare DNS Record: {e}')
        return False

if __name__ == '__main__':
    main()

Be sure to also create a JSON Config file with your API parameters and name it “config.json”:

{
    "zone_name": "example.com",
    "record_name": "home.example.com",
    "email": "[email protected]",
    "token": "your-api-key"
}

I hope this helps! Let me know if you have any other questions.

Leave a Comment

Your email address will not be published. Required fields are marked *