72 lines
2.7 KiB
Python
72 lines
2.7 KiB
Python
import yaml
|
|
import requests
|
|
import re
|
|
import os
|
|
|
|
# Cloudflare API Konfiguration
|
|
CLOUDFLARE_API_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
|
|
CLOUDFLARE_ZONE_ID = os.getenv("CLOUDFLARE_ZONE_ID")
|
|
CLOUDFLARE_API_URL = f"https://api.cloudflare.com/client/v4/zones/{CLOUDFLARE_ZONE_ID}/dns_records"
|
|
|
|
HEADERS = {
|
|
"Authorization": f"Bearer {CLOUDFLARE_API_TOKEN}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
def load_domains(file_path="domains.yaml"):
|
|
with open(file_path, "r") as file:
|
|
return yaml.safe_load(file)
|
|
|
|
def is_reserved(domain, reserved_patterns):
|
|
return any(re.match(pattern, domain) for pattern in reserved_patterns)
|
|
|
|
def get_existing_records():
|
|
response = requests.get(CLOUDFLARE_API_URL, headers=HEADERS)
|
|
if response.status_code == 200:
|
|
return {rec["name"]: rec for rec in response.json().get("result", [])}
|
|
return {}
|
|
|
|
def update_cloudflare():
|
|
data = load_domains()
|
|
reserved_patterns = data.get("reserved_domains", [])
|
|
subdomains = {f"{sub['name']}.morlana.page": sub for sub in data.get("subdomains", [])}
|
|
|
|
existing_records = get_existing_records()
|
|
|
|
# Entferne Einträge, die nicht mehr in domains.yaml stehen
|
|
for existing_domain in existing_records:
|
|
if existing_domain.endswith(".morlana.page") and existing_domain not in subdomains:
|
|
record_id = existing_records[existing_domain]["id"]
|
|
response = requests.delete(f"{CLOUDFLARE_API_URL}/{record_id}", headers=HEADERS)
|
|
if response.status_code == 200:
|
|
print(f"Successfully removed {existing_domain}")
|
|
else:
|
|
print(f"Failed to remove {existing_domain}: {response.text}")
|
|
|
|
# Neue Einträge hinzufügen oder bestehende aktualisieren
|
|
for full_domain, subdomain in subdomains.items():
|
|
if is_reserved(full_domain, reserved_patterns):
|
|
print(f"Skipping reserved domain: {full_domain}")
|
|
continue
|
|
|
|
record_data = {
|
|
"type": "CNAME",
|
|
"name": full_domain,
|
|
"content": subdomain["target"],
|
|
"proxied": subdomain.get("proxy", True)
|
|
}
|
|
|
|
if full_domain in existing_records:
|
|
record_id = existing_records[full_domain]["id"]
|
|
response = requests.put(f"{CLOUDFLARE_API_URL}/{record_id}", json=record_data, headers=HEADERS)
|
|
else:
|
|
response = requests.post(CLOUDFLARE_API_URL, json=record_data, headers=HEADERS)
|
|
|
|
if response.status_code in [200, 201]:
|
|
print(f"Successfully updated {full_domain}")
|
|
else:
|
|
print(f"Failed to update {full_domain}: {response.text}")
|
|
|
|
if __name__ == "__main__":
|
|
update_cloudflare()
|