Skip to content

Instantly share code, notes, and snippets.

@abdusco
Created February 20, 2021 10:03
Show Gist options
  • Save abdusco/7ba5f120daab4f39ca24bee8ee397712 to your computer and use it in GitHub Desktop.
Save abdusco/7ba5f120daab4f39ca24bee8ee397712 to your computer and use it in GitHub Desktop.
Create Cloudflare DNS records with Python
import logging
from os import getenv
import httpx
logging.basicConfig(level=logging.DEBUG)
# go to https://dash.cloudflare.com/profile/api-tokens
# and create a token with Zone.DNS permissions
CLOUDFLARE_TOKEN = getenv('CLOUDFLARE_TOKEN')
CLOUDFLARE_ZONE = getenv('CLOUDFLARE_ZONE')
http = httpx.Client(
base_url='https://api.cloudflare.com/client/v4',
headers={
'Authorization': f'Bearer {CLOUDFLARE_TOKEN}',
}
)
def add_dns_record(name: str, content: str, type: str = 'A', proxied: bool = False):
res = http.get(f'/zones/{CLOUDFLARE_ZONE}/dns_records')
res.raise_for_status()
records = res.json()
existing: list[str] = [it['id'] for it in records['result'] if it['name'] == name or it['name'].startswith(name)]
logging.info(f'Found existing records for {name=}: {existing}')
logging.info('Removing existing ones')
for id in existing:
http.delete(f'/zones/{CLOUDFLARE_ZONE}/dns_records/{id}')
logging.info('Adding new record')
res = http.post(f'/zones/{CLOUDFLARE_ZONE}/dns_records', json={
'type': type,
'name': name,
'content': content,
'proxied': proxied,
})
res.raise_for_status()
def main():
import argparse
assert CLOUDFLARE_ZONE and CLOUDFLARE_TOKEN
parser = argparse.ArgumentParser()
parser.add_argument('name', help='Name of subdomain, e.g. mail')
parser.add_argument('destination', help='Content, e.g. an IP address for A records: 1.1.1.1')
parser.add_argument('--type', '-t', default='A', help='Record type, e.g. A, CNAME, TXT')
args = parser.parse_args()
add_dns_record(name=args.name, content=args.destination, type=args.type)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment