feat: only update if destination changed

This commit is contained in:
Daniel Langbein 2023-03-28 16:46:13 +02:00
parent 6c04860119
commit c2b7f3284b

View File

@ -33,19 +33,44 @@ def main():
type_ = cfg[domain]['type'].upper() type_ = cfg[domain]['type'].upper()
if type_ == 'A': if type_ == 'A':
destination = external_ipv4() destination = external_ipv4()
update_record_destination(api, domain, hostname, type_, destination=destination) if update_record_destination(api, domain, hostname, type_, destination=destination):
print(f'Set {hostname}.{domain} {type_} record to {destination}') print(f'Set {hostname}.{domain} {type_} record to {destination}')
else:
print(f'The {hostname}.{domain} {type_} record points already to {destination}.')
else: else:
raise Exception(f'DNS record type {type_} is not supported.') raise Exception(f'DNS record type {type_} is not supported.')
def update_record_destination(api: Client, domain: str, hostname: str, type_: str, destination: str) -> None: def update_record_destination(api: Client, domain: str, hostname: str, type_: str, destination: str) -> bool:
"""
Updates the `destination` of the DNS record identified by `domain`, `hostname` and `type`.
:param api:
:param domain:
:param hostname:
:param type_:
:param destination:
:return: True if `destination` differs from the old destination.
"""
record = get_record(api, domain, hostname, type_) record = get_record(api, domain, hostname, type_)
if record.destination == destination:
# The new destination is identical with the current one.
# Thus, we don't need to call the api.update_dns_record() method.
return False
else:
record.destination = destination record.destination = destination
api.update_dns_record(domain, record) api.update_dns_record(domain, record)
return True
def get_record(api: Client, domain: str, hostname: str, type_: str) -> DNSRecord: def get_record(api: Client, domain: str, hostname: str, type_: str) -> DNSRecord:
"""
:param api:
:param domain:
:param hostname:
:param type_:
:return: The DNS record identified by `domain`, `hostname` and `type`.
"""
records: list[DNSRecord] = api.dns_records(domain) records: list[DNSRecord] = api.dns_records(domain)
record: DNSRecord record: DNSRecord