-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathensure_cloudflare_pages.py
More file actions
executable file
·144 lines (117 loc) · 4.78 KB
/
Copy pathensure_cloudflare_pages.py
File metadata and controls
executable file
·144 lines (117 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
"""Idempotently configure a Cloudflare Pages project, custom domain, and DNS."""
from __future__ import annotations
import argparse
import json
import os
import urllib.error
import urllib.parse
import urllib.request
API = "https://api.cloudflare.com/client/v4"
def request(method: str, url: str, token: str, payload: dict[str, object] | None = None) -> dict[str, object]:
data = None if payload is None else json.dumps(payload).encode()
req = urllib.request.Request(
url,
data=data,
method=method,
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
body = resp.read().decode()
except urllib.error.HTTPError as exc:
body = exc.read().decode()
try:
parsed = json.loads(body) if body else {}
except json.JSONDecodeError:
parsed = {"raw": body}
raise SystemExit(f"{method} {url} failed: HTTP {exc.code} {parsed}") from exc
parsed = json.loads(body) if body else {}
if not parsed.get("success", True):
raise SystemExit(f"{method} {url} failed: {parsed}")
return parsed
def ensure_project(account_id: str, token: str, project: str, branch: str) -> str:
url = f"{API}/accounts/{account_id}/pages/projects/{project}"
try:
result = request("GET", url, token)
print(f"project exists: {project}")
return result["result"]["subdomain"]
except SystemExit as exc:
if "HTTP 404" not in str(exc):
raise
result = request(
"POST",
f"{API}/accounts/{account_id}/pages/projects",
token,
{"name": project, "production_branch": branch},
)
print(f"created project: {project}")
return result["result"]["subdomain"]
def ensure_custom_domain(account_id: str, token: str, project: str, domain: str) -> None:
base = f"{API}/accounts/{account_id}/pages/projects/{project}/domains"
try:
request("GET", f"{base}/{domain}", token)
print(f"domain exists: {domain}")
return
except SystemExit as exc:
if "HTTP 404" not in str(exc):
raise
request("POST", base, token, {"name": domain})
print(f"attached domain: {domain}")
def find_zone(token: str, zone_name: str) -> str:
query = urllib.parse.urlencode({"name": zone_name})
result = request("GET", f"{API}/zones?{query}", token)
zones = result.get("result") or []
if not zones:
raise SystemExit(f"zone not found: {zone_name}")
return zones[0]["id"]
def ensure_dns(token: str, zone_name: str, domain: str, target: str) -> None:
zone_id = find_zone(token, zone_name)
base = f"{API}/zones/{zone_id}/dns_records"
query = urllib.parse.urlencode({"name": domain})
result = request("GET", f"{base}?{query}", token)
payload = {"type": "CNAME", "name": domain, "content": target, "ttl": 1, "proxied": True}
matches = result.get("result") or []
if matches:
record_id = matches[0]["id"]
record = matches[0]
if (
record.get("type") == payload["type"]
and record.get("content") == payload["content"]
and record.get("proxied") is True
):
print(f"DNS exists: {domain} -> {target}")
return
request("PUT", f"{base}/{record_id}", token, payload)
print(f"updated DNS: {domain} -> {target}")
return
request("POST", base, token, payload)
print(f"created DNS: {domain} -> {target}")
def default_zone(domain: str) -> str:
parts = domain.split(".")
if len(parts) < 2:
raise SystemExit(f"cannot infer zone from domain: {domain}")
return ".".join(parts[-2:])
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--project", required=True)
parser.add_argument("--domain")
parser.add_argument("--zone")
parser.add_argument("--branch", default="main")
parser.add_argument("--dns-target")
args = parser.parse_args()
account_id = os.environ["CLOUDFLARE_ACCOUNT_ID"]
token = os.environ["CLOUDFLARE_API_TOKEN"]
# The pages.dev subdomain is not always {project}.pages.dev: when the
# name is taken globally, Cloudflare assigns a suffixed one. A CNAME at
# the guessed name points at a stranger's project and the custom domain
# never validates, so always ask the API for the real subdomain.
subdomain = ensure_project(account_id, token, args.project, args.branch)
if args.domain:
target = args.dns_target or subdomain
zone = args.zone or default_zone(args.domain)
ensure_custom_domain(account_id, token, args.project, args.domain)
ensure_dns(token, zone, args.domain, target)
return 0
if __name__ == "__main__":
raise SystemExit(main())