Created
August 24, 2025 14:37
-
-
Save BoogerMan2103/b6f261b9347ab37c9909fa372ed9e153 to your computer and use it in GitHub Desktop.
Script to create A record to cloudflare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| import http.client | |
| import json | |
| import logging | |
| import os | |
| import sys | |
| # Initialize logger to output to stderr | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(levelname)s - %(message)s", | |
| stream=sys.stderr, | |
| ) | |
| CLOUDFLARE_ZONE_ID = os.getenv("CLOUDFLARE_ZONE_ID") | |
| CLOUDFLARE_TOKEN = os.getenv("CLOUDFLARE_TOKEN") | |
| def create_cloudflare_dns_record(server_name, server_ip): | |
| """Create DNS A record in Cloudflare""" | |
| url = f"/client/v4/zones/{CLOUDFLARE_ZONE_ID}/dns_records" | |
| headers = { | |
| "Authorization": f"Bearer {CLOUDFLARE_TOKEN}", | |
| "Content-Type": "application/json", | |
| } | |
| data = { | |
| "type": "A", | |
| "name": server_name, | |
| "content": server_ip, | |
| "ttl": 1, | |
| "proxied": False, | |
| } | |
| try: | |
| logging.info(f"Creating Cloudflare DNS record: {data}") | |
| conn = http.client.HTTPSConnection("api.cloudflare.com") | |
| conn.request( | |
| method="POST", | |
| url=url, | |
| headers=headers, | |
| body=json.dumps(data), | |
| ) | |
| response = conn.getresponse() | |
| if response.status >= 200 and response.status < 300: | |
| logging.info(f"Cloudflare API response: {response.read().decode('utf8')}") | |
| conn.close() | |
| return True, None | |
| else: | |
| error_msg = f"Failed to create DNS record. Status code: {response.status}" | |
| if hasattr(response, "read"): | |
| error_msg += f"\nResponse: {response.read().decode('utf8')}" | |
| logging.error(error_msg) | |
| conn.close() | |
| return False, error_msg | |
| except Exception as e: | |
| error_msg = f"Cloudflare API error: {str(e)}" | |
| if hasattr(e, "message"): | |
| error_msg += f"\nMessage: {e.__str__()}" | |
| logging.error(error_msg) | |
| return False, error_msg | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Create Cloudflare DNS A record") | |
| parser.add_argument( | |
| "server_name", type=str, help="The name of the server (subdomain)" | |
| ) | |
| parser.add_argument( | |
| "server_ip", type=str, help="The IP address to map to the server" | |
| ) | |
| args = parser.parse_args() | |
| create_cloudflare_dns_record(args.server_name, args.server_ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment