Skip to content

Instantly share code, notes, and snippets.

@costa86
Last active December 2, 2021 12:34
Show Gist options
  • Save costa86/c270675926161aafcb1f4e12744e9010 to your computer and use it in GitHub Desktop.
Save costa86/c270675926161aafcb1f4e12744e9010 to your computer and use it in GitHub Desktop.
CloudFare API as CLI
import click
import requests
ZONE = "<zone>"
API_VERSION = 4
TYPE_TYPES = list(set(["CAA","A","AAAA","CNAME","URI","MX","SRV","URI","TXT","CERT","DS","HTTPS","LOC","NAPTR","NS","PTR","SMIMEA","SPF","SRV","SSHFP","SVCB","TLSA","TXT"]))
TYPE_TYPES.sort()
defaults = {
"email": "<email>",
"token": "<token>",
"url": f"https://api.cloudflare.com/client/v{API_VERSION}/zones/{ZONE}/dns_records",
"content": "<ip>",
"type": "A",
"ttl": 1,
"priority": 10,
"proxied": True
}
def call_cloudfare_api(json_data: dict) -> dict:
headers = {
"Content-Type": "application/json",
"X-Auth-Email": defaults["email"],
"X-Auth-Key": defaults["token"]
}
r = requests.post(url=defaults["url"], headers=headers, json=json_data)
return r.json()
@click.command()
@click.option('--name', help='DNS record name (customer name)')
@click.option('--content', default=defaults["content"],show_default=True, help=f'DNS record content.')
@click.option('--type', default=defaults["type"],show_default=True,type=click.Choice(TYPE_TYPES), help=f'DNS record type'.)
@click.option('--ttl', default=defaults["ttl"],show_default=True, help=f'Time to live for DNS record. Value of 1 is "automatic".')
@click.option('--priority', default=defaults["priority"],show_default=True, help=f'Required for MX, SRV and URI records; unused by other record types. Records with lower priorities are preferred.')
@click.option('--proxied', default=defaults["proxied"],show_default=True, help=f'Whether the record is receiving the performance and security benefits of Cloudflare.')
def start(**kwargs):
"""Program to create a new DNS entry on CloudFare via its API."""
name = kwargs["name"]
content = kwargs["content"]
record_type = kwargs["type"]
ttl = kwargs["ttl"]
priority = kwargs["priority"]
proxied = kwargs["proxied"]
if not name:
click.echo("--help")
return click.echo("Name is required")
request_data = {
"type": record_type,
"name": name,
"content": content,
"ttl": ttl,
"priority": priority,
"proxied": proxied
}
api_call = call_cloudfare_api(request_data)
click.echo(api_call)
if __name__ == '__main__':
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment