Skip to content

Instantly share code, notes, and snippets.

@almazkun
Last active February 4, 2022 10:30
Show Gist options
  • Save almazkun/bb15b3fc54ec6cbe7476b52c49e7c4aa to your computer and use it in GitHub Desktop.
Save almazkun/bb15b3fc54ec6cbe7476b52c49e7c4aa to your computer and use it in GitHub Desktop.
Cloudflare bulk delete dns
"""
This module is contains a handy tool to bulk delete DNS records from Cloudflare DNS via API
Usage:
```bash
git clone https://gist.github.com/bb15b3fc54ec6cbe7476b52c49e7c4aa.git
cd bb15b3fc54ec6cbe7476b52c49e7c4aa
python3 ./cloudflare_bulk_delete_dns.py your_api_token zone_id
```
"""
import requests as r
import sys
API_TOKEN = "https://dash.cloudflare.com/profile/api-tokens"
ZONE_ID = "https://dash.cloudflare.com#Overview#API#Zone_ID"
def del_dns(id: str, api_token: str = API_TOKEN, zone_id: str = ZONE_ID) -> str:
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{id}"
headers = {"Authorization": f"Bearer {api_token}"}
res = r.delete(url, headers=headers)
if res.ok:
print("\tDeleted:", res.json())
res.raise_for_status()
def del_all_dns(api_token: str = API_TOKEN, zone_id: str = ZONE_ID):
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
headers = {"Authorization": f"Bearer {api_token}"}
params = {
"per_page": 100,
}
while True:
print("\n\tDeleting ALL dns records\n")
res = r.get(url, params=params, headers=headers)
if res.ok:
result = res.json().get("result")
result_info = res.json().get("result_info")
total_count = result_info.get("total_count")
print(f"\tTotal DNS count: {total_count}!")
if total_count == 0:
print("\n\tDone!\n")
return
for record in result:
del_dns(id=record.get("id"), api_token=api_token, zone_id=zone_id)
res.raise_for_status()
if __name__ == "__main__":
del_all_dns(api_token=sys.argv[1], zone_id=sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment