Skill: xieyuanqing/cloudflare-dns-updater (version 0.1.1)

--- name: cloudflare-dns-updater description: "Creates or updates a proxied Cloudflare DNS A record. Use when you need to programmatically point a subdomain to an IP address. Takes record name, zone name, and IP address as input." metadata: openclaw: requires: bins: ["python3"] python: ["requests"] --- # Cloudflare DNS Updater This skill creates or updates a Cloudflare DNS 'A' record, pointing it to a specified IP address and ensuring it is proxied. It is a foundational tool for automating service deployment and DNS management. ## Pre-requisites This skill requires the `CLOUDFLARE_API_TOKEN` environment variable to be set with a valid Cloudflare API Token that has DNS edit permissions. The model should verify this prerequisite before attempting to use the skill. If the variable is not set, it should inform the user and stop. ## Core Action: `scripts/update-record.py` The core logic is handled by the `update-record.py` script. ### **Inputs (Command-Line Arguments)** - `--zone`: (Required) The root domain name. Example: `example.com` - `--record`: (Required) The name of the record (subdomain). Use `@` for the root domain itself. Example: `www` - `--ip`: (Required) The IPv4 address to point the record to. - `--proxied`: (Optional) Boolean (`true` or `false`) to set the Cloudflare proxy status. Defaults to `true`. ### **Output** The script will print its progress to stdout. - On success, it prints a confirmation message and a JSON object of the created/updated record. - On failure, it prints a descriptive error message to stderr and exits with a non-zero status code. ### **Execution Workflow** To use this skill, follow these steps: 1. **Verify Prerequisites**: Check if the `CLOUDFLARE_API_TOKEN` environment variable is set. If not, notify the user and abort. 2. **Gather Inputs**: From the user's request, identify the `zone`, `record` name, and target `ip`. 3. **Construct Command**: Build the full shell command to execute the script. 4. **Execute Command**: Run the command using the `exec` tool. 5. **Report Result**: - If the command succeeds, report the successful creation or update to the user. - If the command fails, analyze the error message from stderr and report the issue to the user in a clear, understandable way. ### **Example Usage** **User Request:** "Point www.example.com to the server's public IP." **AI's Thought Process:** 1. The user wants to update a DNS record on Cloudflare. The `cloudflare-dns-updater` skill is perfect for this. 2. I will use the `update-record.py` script. 3. I need the zone, record name, and IP. - Zone: `example.com` - Record: `www` - IP: I need to find the server's public IP first. I can use `curl -s https://ipv4.icanhazip.com/`. 4. I will first get the IP, then construct the final command. 5. I will execute the command and report the outcome. **AI's Actions:** ```bash # Step 1: Get IP PUBLIC_IP=$(curl -s https://ipv4.icanhazip.com/) # Step 2: Run the skill's script python3 skills/cloudflare-dns-updater/scripts/update-record.py \ --zone "example.com" \ --record "www" \ --ip "$PUBLIC_IP" ``` ### **Failure Strategy** - **If `CLOUDFLARE_API_TOKEN` is not set:** Do not attempt to run the script. Inform the user that the required environment variable is missing and needs to be configured by the administrator. - **If the script exits with an error:** Read the error message from stderr. Common errors include invalid API token, incorrect zone name, or insufficient permissions. Report the specific error to the user.

path: README.md
content: # Cloudflare DNS Updater Skill

This is a skill for AI agents that provides a robust, stateless command-line script to create or update Cloudflare DNS 'A' records.

## Features

- **Stateless Design**: All required configuration (except for the API token) is passed via command-line arguments, making it ideal for automated, agent-driven workflows.
- **Environment-based Authentication**: Securely reads the Cloudflare API Token from an environment variable.
- **Idempotent**: Safely creates a new record or updates an existing one.

## Prerequisites

Before using the script, the `CLOUDFLARE_API_TOKEN` environment variable must be set on the host system.

```bash
export CLOUDFLARE_API_TOKEN="your_cloudflare_api_token"
```

The token requires DNS edit permissions for the specified zone.

## Usage

The core logic is contained within `scripts/update-record.py`.

### Arguments

- `--zone` (Required): The root domain name (e.g., `example.com`).
- `--record` (Required): The name of the record (subdomain). Use `@` for the root domain itself.
- `--ip` (Required): The IPv4 address for the 'A' record.
- `--proxied` (Optional): `true` or `false` to set the Cloudflare proxy status. Defaults to `true`.

### Example

```bash
python3 scripts/update-record.py \
  --zone "example.com" \
  --record "www" \
  --ip "192.0.2.1"
```

## Included in this Skill

- `SKILL.md`: The manifest file for the AI agent.
- `scripts/update-record.py`: The Python script that performs the DNS update.


path: requirements.txt
content: requests


path: scripts/update-record.py
content: #!/usr/bin/env python3
#!/usr/bin/env python3
import os
import sys
import json
import requests
import argparse

def main():
    parser = argparse.ArgumentParser(description="Create or update a Cloudflare DNS A record.")
    parser.add_argument("--zone", required=True, help="The DNS zone name (e.g., your-domain.com)")
    parser.add_argument("--record", required=True, help="The record name (e.g., 'subdomain' for subdomain.your-domain.com)")
    parser.add_argument("--ip", required=True, help="The IP address to point the record to.")
    parser.add_argument("--proxied", type=lambda x: (str(x).lower() == 'true'), default=True, help="Whether the record is proxied by Cloudflare (default: True)")
    args = parser.parse_args()

    api_token = os.getenv("CLOUDFLARE_API_TOKEN")
    if not api_token:
        print("Error: CLOUDFLARE_API_TOKEN environment variable not set.", file=sys.stderr)
        sys.exit(1)

    headers = {
        "Authorization": f"Bearer {api_token}",
        "Content-Type": "application/json",
    }
    
    full_record_name = f"{args.record}.{args.zone}" if args.record != '@' and args.record != args.zone else args.zone

    # --- Get Zone ID ---
    try:
        zone_id_url = f"https://api.cloudflare.com/client/v4/zones?name={args.zone}"
        response = requests.get(zone_id_url, headers=headers, timeout=10)
        response.raise_for_status()
        zone_data = response.json()
        if not zone_data.get("result"):
            print(f"Error: Could not find Zone ID for '{args.zone}'. Response: {zone_data}", file=sys.stderr)
            sys.exit(1)
        zone_id = zone_data["result"][0]["id"]
        print(f"Found Zone ID: {zone_id} for zone '{args.zone}'")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching Zone ID: {e}", file=sys.stderr)
        sys.exit(1)

    # --- Check for existing Record ---
    try:
        record_url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?type=A&name={full_record_name}"
        response = requests.get(record_url, headers=headers, timeout=10)
        response.raise_for_status()
        record_data = response.json()
        existing_records = record_data.get("result", [])
    except requests.exceptions.RequestException as e:
        print(f"Error fetching DNS records: {e}", file=sys.stderr)
        sys.exit(1)

    # --- Create or Update ---
    payload = {
        "type": "A",
        "name": full_record_name,
        "content": args.ip,
        "ttl": 1,  # 1 for auto
        "proxied": args.proxied,
    }

    try:
        if existing_records:
            record_id = existing_records[0]["id"]
            print(f"Record '{full_record_name}' already exists (ID: {record_id}). Updating IP to {args.ip}...")
            update_url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}"
            response = requests.put(update_url, headers=headers, json=payload, timeout=10)
        else:
            print(f"Record '{full_record_name}' does not exist. Creating new record...")
            create_url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
            response = requests.post(create_url, headers=headers, json=payload, timeout=10)

        response.raise_for_status()
        result = response.json()

        if result.get("success"):
            print(f"Successfully {'updated' if existing_records else 'created'} DNS record for '{full_record_name}'.")
            print(json.dumps(result['result'], indent=2))
        else:
            print(f"Error in API response: {result.get('errors')}", file=sys.stderr)
            sys.exit(1)

    except requests.exceptions.RequestException as e:
        print(f"Error during record {'update' if existing_records else 'creation'}: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (MEDIUM)