Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

Cloudflare detail { "credentials" : { "accountId" : "66cd45876e8d785326d439", "token":…

  1. User

    Cloudflare detail

    { "credentials" : { "accountId" : "66cd45876e8d785326d439", "token": "9rdS_iQ4GexfUDNM_CHPzbuJqRA" },

    "record" : {
        "zone" : "34e2aa3dcff21eea38e9d2cb2df24460",
        "dynamaic" : [
            { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "yun"},
            { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "jelly"},
            { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "wire"},
            { "domain":"marco-leong.com", "ttl": 1800, "type": "A", "name": "note"}
        ],
        "static" : [
            {"domain": "marco-leong.com", "ttl": 1800, "type": "A", "name": "gate", "ip": "10.1.1.1"}
        ]
    }
    

    }

    create a python script to read the above settings from a file named "config.json" in the same directory. Then check the current external ip and compare with the cloudflare record using te credentials provided. If the exteranl ip was updated by the isp, using the cloudflare api to update each of the ip of the records according to the dynamic array. As for the static array, only need to check if it exists and insert the new record if it doesn't.

  2. Assistant

    To create a Python script that reads Cloudflare settings from a JSON file, checks the current external IP, compares it with the existing DNS records, and updates them via the Cloudflare API as necessary, you can use the following code. This script uses the requests library to interact with the Cloudflare API and socket and requests libraries to fetch the current external IP.

    Prerequisites:

    1. Install the requests library if it's not already installed:

      pip install requests
      
    2. Create a file named config.json and insert the Cloudflare settings you provided above.

    Python Script

    Here is the Python script:

    import json
    import requests
    
    # Load the configuration from the JSON file
    with open('config.json', 'r') as file:
        config = json.load(file)
    
    # Get current external IP
    def get_external_ip():
        response = requests.get('https://api.ipify.org')
        return response.text
    
    # Fetch existing DNS records from Cloudflare
    def get_existing_records(account_id, zone_id, token):
        url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
        response = requests.get(url, headers=headers)
        return response.json()
    
    # Update DNS records in Cloudflare
    def update_dns_record(record_id, account_id, zone_id, token, ip, name):
        url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}"
        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
        data = {
            'type': 'A',
            'name': name,
            'content': ip,
            'ttl': 1800,
            'proxied': False
        }
        response = requests.put(url, headers=headers, json=data)
        return response.json()
    
    # Create new DNS record in Cloudflare
    def create_dns_record(account_id, zone_id, token, ip, name):
        url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }
        data = {
            'type': 'A',
            'name': name,
            'content': ip,
            'ttl': 1800,
            'proxied': False
        }
        response = requests.post(url, headers=headers, json=data)
        return response.json()
    
    def main():
        account_id = config['credentials']['accountId']
        token = config['credentials']['token']
        zone_id = config['record']['zone']
        
        current_ip = get_external_ip()
        existing_records = get_existing_records(account_id, zone_id, token)
    
        # Check dynamic records
        for record in config['record']['dynamaic']:
            name = record['name']
            # Check if the record exists
            found = False
            for existing_record in existing_records['result']:
                if existing_record['name'] == name:
                    found = True
                    if existing_record['content'] != current_ip:
                        print(f"Updating record {name} from IP {existing_record['content']} to {current_ip}")
                        update_dns_record(existing_record['id'], account_id, zone_id, token, current_ip, name)
                    break
            if not found:
                print(f"Creating record {name} with IP {current_ip}")
                create_dns_record(account_id, zone_id, token, current_ip, name)
    
        # Check static records
        for static_record in config['record']['static']:
            name = static_record['name']
            # Check if the record exists
            found = False
            for existing_record in existing_records['result']:
                if existing_record['name'] == name:
                    found = True
                    break
            if not found:
                print(f"Creating static record {name} with IP {static_record['ip']}")
                create_dns_record(account_id, zone_id, token, static_record['ip'], name)
    
    if __name__ == "__main__":
        main()
    

    Explanation of the Code

    1. Loading Configurations: The script starts by loading the Cloudflare configurations from config.json.
    2. Fetching Current IP: It uses the ipify API to get the current external IP.
    3. Fetching Existing DNS Records: It queries Cloudflare's API to fetch the existing DNS records in the specified zone.
    4. Updating Dynamic Records: For each dynamic record, it checks if it exists in Cloudflare. If it does and the IP has changed, it updates it. If it doesn't exist, it creates a new DNS record.
    5. Handling Static Records: For static records, it checks if they exist. If not, it creates them with the provided static IP.

    Note

    • Make sure to store your sensitive API tokens securely and avoid hardcoding them directly in your scripts or repositories.