-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfmanager.py
More file actions
834 lines (707 loc) · 27.6 KB
/
Copy pathcfmanager.py
File metadata and controls
834 lines (707 loc) · 27.6 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CLI tools to manage DNS on Cloudflare using Click.
Fully instrumented with logging, validation, and exception handling.
Supports reading CLOUDFLARE_API_TOKEN:
- from the command line via --api-token
- from the environment variable CLOUDFLARE_API_TOKEN
Usage:
python cfmanager.py create-dns-record --zone-name example.com \
--hostname "host.example.com" --type A --value "192.168.1.10"
python cfmanager.py list-dns-zones
python cfmanager.py list-dns-records --zone-name example.com
python cfmanager.py remove-dns-record --zone-name example.com --record-name host.example.com
python cfmanager.py export-dns-zone --zone-name example.com [--output example.com.zone]
Requires:
pip install requests click
"""
import functools
import inspect
import json
import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
import click
import requests
# ------------------------------------------------------------
# Logging configuration
# ------------------------------------------------------------
DEFAULT_LOG_FORMAT = "%(asctime)s | %(levelname)-8s | %(message)s"
DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
DEFAULT_FILE_MAX_BYTES = 1_000_000 # 1 MB
DEFAULT_FILE_BACKUPS = 3
_LOG_CONFIGURED = False
_LOG_FILE_PATH = None
def configure_logging(log_file_path=None):
"""Set up console logging and optional rotating file logging."""
root = logging.getLogger()
root.setLevel(logging.INFO)
# Clear existing handlers to avoid duplication on repeated CLI runs
root.handlers.clear()
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setFormatter(
logging.Formatter(DEFAULT_LOG_FORMAT, DEFAULT_DATE_FORMAT)
)
root.addHandler(console_handler)
if log_file_path:
Path(log_file_path).expanduser().parent.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(
log_file_path,
maxBytes=DEFAULT_FILE_MAX_BYTES,
backupCount=DEFAULT_FILE_BACKUPS,
encoding="utf-8",
)
file_handler.setFormatter(
logging.Formatter(DEFAULT_LOG_FORMAT, DEFAULT_DATE_FORMAT)
)
root.addHandler(file_handler)
def ensure_logging(log_file_path=None):
"""Configure logging once per process."""
global _LOG_CONFIGURED, _LOG_FILE_PATH
if not _LOG_CONFIGURED:
configure_logging(log_file_path)
_LOG_CONFIGURED = True
_LOG_FILE_PATH = log_file_path
return
# If logging already configured without a file, but a file is now provided, add it.
if log_file_path and _LOG_FILE_PATH != log_file_path:
Path(log_file_path).expanduser().parent.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(
log_file_path,
maxBytes=DEFAULT_FILE_MAX_BYTES,
backupCount=DEFAULT_FILE_BACKUPS,
encoding="utf-8",
)
file_handler.setFormatter(
logging.Formatter(DEFAULT_LOG_FORMAT, DEFAULT_DATE_FORMAT)
)
logging.getLogger().addHandler(file_handler)
_LOG_FILE_PATH = log_file_path
logger = logging.getLogger(__name__)
# ------------------------------------------------------------
# Helpers de logging reutilizáveis
# ------------------------------------------------------------
def _build_log_message(message_builder, arguments):
message_data = message_builder(arguments)
if isinstance(message_data, tuple):
message, message_args = message_data
if message_args is None:
message_args = ()
elif isinstance(message_args, list):
message_args = tuple(message_args)
else:
message_args = (message_args,)
else:
message, message_args = message_data, ()
return message, message_args
# ------------------------------------------------------------
# Decorator para logar chamadas de comandos Click
# ------------------------------------------------------------
def log_command_invocation(message_builder):
"""Configura logging e registra a chamada de um comando de forma reutilizável."""
def decorator(func):
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = signature.bind_partial(*args, **kwargs)
bound.apply_defaults()
ctx = click.get_current_context(silent=True)
ctx_obj = (ctx.obj or {}) if ctx else {}
log_file = bound.arguments.get("log_file") or ctx_obj.get("log_file")
ensure_logging(log_file)
message, message_args = _build_log_message(message_builder, bound.arguments)
logger.info(message, *message_args)
bound.arguments["log_file"] = log_file
return func(**bound.arguments)
wrapper.__signature__ = signature # pyright: ignore[reportAttributeAccessIssue]
return wrapper
return decorator
# ------------------------------------------------------------
# Decorator para funções auxiliares (info + captura de erros de rede)
# ------------------------------------------------------------
def log_api_invocation(message_builder=None):
"""
Loga a chamada de uma função auxiliar e converte falhas de rede em ClickException.
message_builder deve receber um dict de argumentos e retornar uma string
ou (string, args) para ser passado ao logger.
"""
def decorator(func):
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = signature.bind_partial(*args, **kwargs)
bound.apply_defaults()
if message_builder:
message, message_args = _build_log_message(
message_builder, bound.arguments
)
logger.info(message, *message_args)
try:
return func(*args, **kwargs)
except click.ClickException:
raise
except requests.exceptions.RequestException as exc:
logger.error("Communication error with Cloudflare: %s", exc)
raise click.ClickException(
f"Communication error with Cloudflare: {exc}"
) from exc
except Exception:
logger.error("Unexpected error in %s", func.__name__, exc_info=True)
raise
wrapper.__signature__ = signature # pyright: ignore[reportAttributeAccessIssue]
return wrapper
return decorator
# ------------------------------------------------------------
# Helper for logging JSON responses
# ------------------------------------------------------------
def _log_response_json(response):
"""Pretty-print a JSON response body for logs, fallback to raw text."""
try:
parsed = response.json()
pretty = json.dumps(parsed, indent=2, ensure_ascii=False)
logger.error("Response JSON:\n%s", pretty)
except ValueError:
logger.error("Response text: %s", response.text)
# ------------------------------------------------------------
# Basic argument validation
# ------------------------------------------------------------
def validate_record_type(record_type):
"""Validate the DNS record type provided by the user."""
valid_types = ["A", "AAAA", "CNAME", "TXT", "MX", "NS", "SRV", "PTR", "CAA"]
if record_type.upper() not in valid_types:
raise ValueError(
f"Invalid type '{record_type}'. Allowed values: {', '.join(valid_types)}"
)
return record_type.upper()
# ------------------------------------------------------------
# Token retrieval (command line or environment variable)
# ------------------------------------------------------------
def get_api_token(cli_token):
"""Retrieve the API token from CLI or environment."""
token = cli_token or os.getenv("CLOUDFLARE_API_TOKEN")
if token:
return token
message = "No token found! Provide --api-token or set CLOUDFLARE_API_TOKEN."
logger.error(message)
raise click.ClickException(message)
# ------------------------------------------------------------
# Create DNS record
# ------------------------------------------------------------
@log_api_invocation(
lambda params: (
"Creating DNS record zone_id=%s host=%s type=%s value=%s",
(params["zone_id"], params["hostname"], params["record_type"], params["value"]),
)
)
def create_dns_record_api(zone_id, api_token, hostname, record_type, value):
"""Create a DNS record using the Cloudflare API."""
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
payload = {
"type": record_type,
"name": hostname,
"content": value,
"ttl": 300, # 5 minutes
"proxied": False, # change to True if you want Cloudflare proxying
}
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
response = requests.post(url, json=payload, headers=headers, timeout=15)
if not response.ok:
message = f"HTTP error while creating record: {response.status_code}"
logger.error(message)
_log_response_json(response)
raise click.ClickException(message)
data = response.json()
if not data.get("success", False):
message = "Failed to create the DNS record on Cloudflare."
logger.error(message)
logger.error("Errors: %s", data.get("errors"))
_log_response_json(response)
raise click.ClickException(message)
logger.info("DNS record created successfully!")
logger.info("Record ID: %s", data["result"]["id"])
logger.debug("Full response: %s", data)
return data
# ------------------------------------------------------------
# List DNS zones
# ------------------------------------------------------------
@log_api_invocation(
lambda params: (
"Listing DNS zones filter=%s page_size=%s",
(params.get("zone_name"), params.get("items_per_page")),
)
)
def list_dns_zones_api(api_token, items_per_page=50, zone_name=None):
"""List DNS zones and return (name, id) pairs, optionally filtered by name."""
url = "https://api.cloudflare.com/client/v4/zones"
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
zones = []
page = 1
while True:
params = {"page": page, "per_page": items_per_page}
if zone_name:
params["name"] = zone_name
response = requests.get(
url,
headers=headers,
params=params,
timeout=15,
)
if not response.ok:
logger.error("HTTP error while listing zones: %s", response.status_code)
_log_response_json(response)
raise click.ClickException(
f"HTTP error while listing zones: {response.status_code}"
)
data = response.json()
if not data.get("success", False):
logger.error("Failed to list zones on Cloudflare.")
logger.error("Errors: %s", data.get("errors"))
_log_response_json(response)
raise click.ClickException("Failed to list zones on Cloudflare.")
zones.extend(
(item.get("name"), item.get("id")) for item in data.get("result", [])
)
result_info = data.get("result_info", {})
if result_info.get("page", page) >= result_info.get(
"total_pages", result_info.get("page", page)
):
break
page += 1
if zone_name and not zones:
logger.info("No zones found for the name: %s", zone_name)
return zones
logger.info("Total zones found: %s", len(zones))
name_width = max((len(name or "") for name, _ in zones), default=0)
for name, zone_id in zones:
logger.info("Zone: %-*s | ID: %s", name_width, name, zone_id)
return zones
# ------------------------------------------------------------
# Utility to get zone_id by name
# ------------------------------------------------------------
@log_api_invocation(lambda params: ("Fetching zone id for %s", (params["zone_name"],)))
def get_zone_id_by_name(api_token, zone_name):
"""Get the zone_id from the exact zone name."""
url = "https://api.cloudflare.com/client/v4/zones"
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
params = {"name": zone_name, "per_page": 1}
response = requests.get(url, headers=headers, params=params, timeout=15)
if not response.ok:
logger.error("HTTP error while fetching zone: %s", response.status_code)
_log_response_json(response)
raise click.ClickException(
f"HTTP error while fetching zone: {response.status_code}"
)
data = response.json()
if not data.get("success", False):
logger.error("Failed to fetch zone on Cloudflare.")
logger.error("Errors: %s", data.get("errors"))
_log_response_json(response)
raise click.ClickException("Failed to fetch zone on Cloudflare.")
results = data.get("result", [])
if not results:
raise click.ClickException(f"Zone not found: {zone_name}")
zone_id = results[0].get("id")
logger.info("Zone found: %s | ID: %s", zone_name, zone_id)
return zone_id
# ------------------------------------------------------------
# Find and remove DNS record
# ------------------------------------------------------------
@log_api_invocation(
lambda params: (
"Looking up DNS record zone_id=%s name=%s",
(params["zone_id"], params["record_name"]),
)
)
def find_dns_record_by_name(zone_id, api_token, record_name):
"""Find a DNS record by exact name within a zone."""
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
params = {"name": record_name, "per_page": 100}
response = requests.get(url, headers=headers, params=params, timeout=15)
if not response.ok:
logger.error("HTTP error while fetching DNS record: %s", response.status_code)
_log_response_json(response)
raise click.ClickException(
f"HTTP error while fetching DNS record: {response.status_code}"
)
data = response.json()
if not data.get("success", False):
logger.error("Failed to fetch DNS record on Cloudflare.")
_log_response_json(response)
raise click.ClickException("Failed to fetch DNS record on Cloudflare.")
records = [rec for rec in data.get("result", []) if rec.get("name") == record_name]
if not records:
raise click.ClickException(f"DNS record not found: {record_name}")
if len(records) > 1:
raise click.ClickException(
f"Multiple DNS records found for {record_name}; refine the query."
)
record = records[0]
logger.info(
"Record found: %s | Type: %s | Content: %s | ID: %s",
record.get("name"),
record.get("type"),
record.get("content"),
record.get("id"),
)
return record
@log_api_invocation(
lambda params: (
"Deleting DNS record zone_id=%s record_id=%s",
(params["zone_id"], params["record_id"]),
)
)
def remove_dns_record_api(zone_id, api_token, record_id):
"""Remove a DNS record using the Cloudflare API."""
url = (
f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}"
)
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
response = requests.delete(url, headers=headers, timeout=15)
if not response.ok:
message = f"HTTP error while deleting record: {response.status_code}"
logger.error(message)
_log_response_json(response)
raise click.ClickException(message)
data = response.json()
if not data.get("success", False):
message = "Failed to delete the DNS record on Cloudflare."
logger.error(message)
_log_response_json(response)
raise click.ClickException(message)
logger.info("DNS record deleted successfully!")
return data
@log_api_invocation(
lambda params: ("Exporting DNS zone zone_id=%s", (params["zone_id"],))
)
def export_dns_zone_api(zone_id, api_token):
"""Export DNS records of a zone in BIND format."""
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/export"
headers = {
"Authorization": f"Bearer {api_token}",
}
response = requests.get(url, headers=headers, timeout=30)
if not response.ok:
logger.error("HTTP error while exporting zone: %s", response.status_code)
_log_response_json(response)
raise click.ClickException(
f"HTTP error while exporting zone: {response.status_code}"
)
return response.text
@log_api_invocation(
lambda params: (
"Listing DNS records zone_id=%s page_size=%s",
(params["zone_id"], params["items_per_page"]),
)
)
def list_dns_records_api(zone_id, api_token, items_per_page=100):
"""List DNS records for a zone."""
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
records = []
page = 1
while True:
params = {"page": page, "per_page": items_per_page}
response = requests.get(url, headers=headers, params=params, timeout=15)
if not response.ok:
logger.error(
"HTTP error while listing DNS records: %s", response.status_code
)
_log_response_json(response)
raise click.ClickException(
f"HTTP error while listing DNS records: {response.status_code}"
)
data = response.json()
if not data.get("success", False):
logger.error("Failed to list DNS records on Cloudflare.")
_log_response_json(response)
raise click.ClickException("Failed to list DNS records on Cloudflare.")
records.extend(data.get("result", []))
info = data.get("result_info", {})
if info.get("page", page) >= info.get("total_pages", info.get("page", page)):
break
page += 1
logger.info("Total DNS records found: %s", len(records))
return records
def _print_dns_records_table(records):
"""Pretty-print DNS records as a table."""
if not records:
click.echo("No DNS records found.")
return
headers = ["HOSTNAME", "TYPE", "DESTINATION"]
max_dest_width = 80 # avoid overly wide tables for very long values
def _shorten(value, limit):
if len(value) <= limit:
return value
return value[: limit - 3] + "..."
rows = []
for rec in records:
name = str(rec.get("name", ""))
rtype = str(rec.get("type", ""))
content_raw = str(rec.get("content", ""))
if rtype.upper() == "MX":
priority = rec.get("priority")
if priority is not None:
content_raw = f"{priority} {content_raw}"
content = _shorten(content_raw, max_dest_width)
rows.append([name, rtype, content])
col_widths = [
max(len(headers[i]), max((len(r[i]) for r in rows), default=0))
for i in range(len(headers))
]
fmt = " | ".join(f"{{:<{w}}}" for w in col_widths)
click.echo(fmt.format(*headers))
click.echo("-+-".join("-" * w for w in col_widths))
for row in rows:
click.echo(fmt.format(*row))
# ------------------------------------------------------------
# CLI with Click
# ------------------------------------------------------------
def validate_record_type_callback(_ctx, _param, value):
"""Validate record type for Click options."""
try:
return validate_record_type(value)
except ValueError as exc:
raise click.BadParameter(str(exc)) from exc
@click.group()
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@click.pass_context
def cli(ctx, log_file):
"""CLI tools for DNS management on Cloudflare."""
ensure_logging(log_file)
ctx.ensure_object(dict)
ctx.obj["log_file"] = log_file
@cli.command(name="create-dns-record")
@click.option("--zone-name", required=True, help="Zone name in Cloudflare.")
@click.option(
"--api-token",
envvar="CLOUDFLARE_API_TOKEN",
help="API token with dns.edit permission (or set CLOUDFLARE_API_TOKEN).",
)
@click.option(
"--hostname", required=True, help="Full hostname (e.g., api.example.com)."
)
@click.option(
"--type",
"record_type",
required=True,
callback=validate_record_type_callback,
help="Record type (A, AAAA, CNAME, TXT, MX, NS, SRV, PTR, CAA).",
)
@click.option("--value", required=True, help="IP address or target of the DNS record.")
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@log_command_invocation(
lambda params: (
"Command=create-dns-record zone=%s host=%s type=%s",
(params["zone_name"], params["hostname"], params["record_type"]),
)
)
def create_dns_record(zone_name, api_token, hostname, record_type, value, log_file):
"""Create a host in a specific DNS zone."""
ctx = click.get_current_context()
try:
token = get_api_token(api_token)
zone_id = get_zone_id_by_name(token, zone_name)
response = create_dns_record_api(
api_token=token,
hostname=hostname,
record_type=record_type,
value=value,
zone_id=zone_id,
)
click.echo(json.dumps(response, indent=2))
except Exception as exc:
click.echo(json.dumps({"error": str(exc)}, indent=2), err=True)
ctx.exit(1)
@cli.command(name="list-dns-zones")
@click.option(
"--api-token",
envvar="CLOUDFLARE_API_TOKEN",
help="API token with zone read permission (or set CLOUDFLARE_API_TOKEN).",
)
@click.option(
"--page-size",
default=50,
show_default=True,
help="Number of zones per page in the paginated request.",
)
@click.option(
"--zone-name",
help="Exact zone name to filter (e.g., example.com).",
)
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@log_command_invocation(
lambda params: (
"Command=list-dns-zones zone_filter=%s page_size=%s",
(params["zone_name"], params["page_size"]),
)
)
def list_dns_zones(api_token, page_size, zone_name, log_file):
"""List DNS zones (all or filtered by name) and show their names and IDs."""
ctx = click.get_current_context()
try:
token = get_api_token(api_token)
list_dns_zones_api(
api_token=token,
items_per_page=page_size,
zone_name=zone_name,
)
except Exception as exc:
click.echo(json.dumps({"error": str(exc)}, indent=2), err=True)
ctx.exit(1)
@cli.command(name="remove-dns-record")
@click.option("--zone-name", required=True, help="Zone name in Cloudflare.")
@click.option(
"--api-token",
envvar="CLOUDFLARE_API_TOKEN",
help="API token with dns.edit permission (or set CLOUDFLARE_API_TOKEN).",
)
@click.option(
"--record-name",
required=True,
help="Full record name to remove (e.g., passbolt.example.com).",
)
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@log_command_invocation(
lambda params: (
"Command=remove-dns-record zone=%s record=%s",
(params["zone_name"], params["record_name"]),
)
)
def remove_dns_record(zone_name, api_token, record_name, log_file):
"""Remove a DNS record from a specific zone after user confirmation."""
ctx = click.get_current_context()
try:
token = get_api_token(api_token)
zone_id = get_zone_id_by_name(token, zone_name)
record = find_dns_record_by_name(zone_id, token, record_name)
prompt = (
f"Remove record '{record_name}' (type {record.get('type')}) "
f"from zone '{zone_name}'?"
)
if not click.confirm(prompt, default=False):
click.echo(json.dumps({"status": "cancelled"}, indent=2))
return
response = remove_dns_record_api(zone_id, token, record.get("id"))
click.echo(json.dumps(response, indent=2))
except Exception as exc:
click.echo(json.dumps({"error": str(exc)}, indent=2), err=True)
ctx.exit(1)
@cli.command(name="list-dns-records")
@click.option("--zone-name", required=True, help="Zone name in Cloudflare.")
@click.option(
"--api-token",
envvar="CLOUDFLARE_API_TOKEN",
help="API token with dns.read permission (or set CLOUDFLARE_API_TOKEN).",
)
@click.option(
"--page-size",
default=100,
show_default=True,
help="Number of records per page in the paginated request.",
)
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@log_command_invocation(
lambda params: (
"Command=list-dns-records zone=%s page_size=%s",
(params["zone_name"], params["page_size"]),
)
)
def list_dns_records(zone_name, api_token, page_size, log_file):
"""List DNS records of a zone in a table."""
ctx = click.get_current_context()
try:
token = get_api_token(api_token)
zone_id = get_zone_id_by_name(token, zone_name)
records = list_dns_records_api(zone_id, token, items_per_page=page_size)
_print_dns_records_table(records)
except Exception as exc:
click.echo(json.dumps({"error": str(exc)}, indent=2), err=True)
ctx.exit(1)
@cli.command(name="export-dns-zone")
@click.option("--zone-name", required=True, help="Zone name in Cloudflare.")
@click.option(
"--api-token",
envvar="CLOUDFLARE_API_TOKEN",
help="API token with dns.read permission (or set CLOUDFLARE_API_TOKEN).",
)
@click.option(
"--output",
"output_path",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Output file path (defaults to <zone-name>.zone).",
)
@click.option(
"--log-file",
type=click.Path(dir_okay=False, writable=True, resolve_path=True),
help="Optional log file path; enables rotating logs (1 MB, 3 backups).",
)
@log_command_invocation(
lambda params: (
"Command=export-dns-zone zone=%s output=%s",
(params["zone_name"], params["output_path"]),
)
)
def export_dns_zone(zone_name, api_token, output_path, log_file):
"""Export DNS records of a zone to a BIND9-style file."""
ctx = click.get_current_context()
try:
token = get_api_token(api_token)
zone_id = get_zone_id_by_name(token, zone_name)
zone_bind = export_dns_zone_api(zone_id, token)
if output_path:
path = Path(output_path)
else:
safe_name = zone_name.replace("/", "_")
path = Path(f"{safe_name}.zone")
path.write_text(zone_bind, encoding="utf-8")
click.echo(json.dumps({"status": "ok", "file": str(path)}, indent=2))
except Exception as exc:
click.echo(json.dumps({"error": str(exc)}, indent=2), err=True)
ctx.exit(1)
# ------------------------------------------------------------
# Execution
# ------------------------------------------------------------
if __name__ == "__main__":
cli()