Skip to content

Instantly share code, notes, and snippets.

@nwithan8
Created January 8, 2021 02:10
Show Gist options
  • Select an option

  • Save nwithan8/bd3067b3bc685147b4bed1676bdf14ae to your computer and use it in GitHub Desktop.

Select an option

Save nwithan8/bd3067b3bc685147b4bed1676bdf14ae to your computer and use it in GitHub Desktop.
Update all A records for a CloudFlare domain
import CloudFlare
import argparse
import ipify2
CLOUDFLARE_API_KEY = "XXXXXX"
parser = argparse.ArgumentParser(description="Update all CloudFlare DNS entries for a subdomain with a new IP address")
parser.add_argument('domain',
type=str,
help='Base domain')
parser.add_argument('-e',
'--external_ip',
type=str,
help="External IP address")
parser.add_argument('-6',
'--ipv6',
action='store_true',
help="Use IPV6 address")
args = parser.parse_args()
if not args.external_ip:
args.external_ip = ipify2.ipify.get_universal_ip() if args.ipv6 else ipify2.ipify.get_ipv4()
if not args.external_ip:
raise Exception("Could not get IP address.")
def parse_subdomain(domain):
split = domain.split(".")
if len(split) == 2:
return domain
return domain.split(".")[0]
def make_dns_record(subdomain, zone_id, ip_address, IPV6: bool = False, proxied: bool = True):
new_record = {'name': subdomain, 'type': ('AAAA' if IPV6 else 'A'), 'content': ip_address, 'proxied': proxied}
print(new_record)
if not cf.zones.dns_records.post(zone_id, data=new_record):
raise Exception("Could not make DNS entry on CloudFlare.")
cf = CloudFlare.CloudFlare(token=CLOUDFLARE_API_KEY)
zone_id = cf.zones.get(params={'name': args.domain, 'per_page': 1})[0]['id']
for record in cf.zones.dns_records.get(zone_id):
if record.get('type') == 'A':
cf.zones.dns_records.delete(zone_id, record.get('id'))
make_dns_record(subdomain=parse_subdomain(domain=record.get('name')), zone_id=zone_id,
ip_address=args.external_ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment