feat: add WIP Cloudflare handler

This commit is contained in:
ptrcnull 2024-06-12 12:01:26 +02:00
parent 619700d0ea
commit c8c8275da3
Signed by: ptrcnull
GPG key ID: 411F7B30801DD9CA
3 changed files with 54 additions and 1 deletions

View file

@ -1,7 +1,9 @@
from .cloudflare import CloudflareHandler
from .hetzner import HetznerHandler from .hetzner import HetznerHandler
from .http import HTTPHandler from .http import HTTPHandler
__all__ = [ __all__ = [
'CloudflareHandler',
'HetznerHandler', 'HetznerHandler',
'HTTPHandler' 'HTTPHandler'
] ]

View file

@ -0,0 +1,50 @@
import json
import os
import subprocess
from typing import Any
import dns.resolver
from ..config import Config
from .base import Handler
class CloudflareHandler(Handler):
nameservers: list[str]
def __init__(self, zone_name: str, config: Config, token: str) -> None:
super().__init__(zone_name, config, token)
self.secret = config.get_secret('cloudflare')
servers = dns.resolver.resolve(zone_name, 'NS')
self.nameservers = list(map(lambda rdata: str(rdata.target).strip('.'), servers))
def run(self, args: list[str]) -> Any:
env = os.environ.copy()
env['CF_API_TOKEN'] = self.secret
res = subprocess.run(['flarectl', '--json'] + args, check=True, stdout=subprocess.PIPE)
return json.loads(res.stdout)
def create(self, record_name: str, record_value: str) -> None:
full_record_name = record_name + '.' + self.zone
self.remove(record_name)
self.log.info('creating %s with value %s', full_record_name, record_value)
self.run([
'dns', 'create',
'--zone', self.zone,
'--type', 'TXT',
'--name', full_record_name,
'--content', record_value,
])
def remove(self, record_name: str) -> None:
records = self.run(['dns', 'list', '--zone', self.zone])
full_record_name = record_name + '.' + self.zone
for record in records:
if record['Name'] == full_record_name:
self.log.info('removing %s', full_record_name)
self.run([
'dns', 'delete',
'--zone', self.zone,
'--id', record['ID']
])

View file

@ -7,13 +7,14 @@ from itertools import chain
import dns.resolver import dns.resolver
from .config import read_config from .config import read_config
from .handlers import HetznerHandler, HTTPHandler from .handlers import CloudflareHandler, HetznerHandler, HTTPHandler
logging.basicConfig(level=logging.INFO, format='> [%(levelname)s] %(name)s: %(message)s') logging.basicConfig(level=logging.INFO, format='> [%(levelname)s] %(name)s: %(message)s')
log = logging.getLogger('nyacme_hook') log = logging.getLogger('nyacme_hook')
handlers = { handlers = {
'cloudflare': CloudflareHandler,
'hetzner': HetznerHandler, 'hetzner': HetznerHandler,
'http': HTTPHandler, 'http': HTTPHandler,
} }