dns_zone: add support for diff and check modes

This commit is contained in:
jeltz 2022-08-20 04:34:47 +02:00
parent 426296d8bd
commit d5ab886dd4
Signed by: jeltz
GPG key ID: 800882B66C0C3326

View file

@ -308,6 +308,41 @@ def zones_eq(lhs: dns.zone.Zone, rhs: dns.zone.Zone) -> bool:
)
def write_text_file(path, text, module):
"""Naive text file write function with support for Ansible's diff and
check modes."""
diff_text = {
"before_header": f"{path} (content)",
"after_header": f"{path} (content)",
"after": text,
}
try:
with open(path) as f:
current = f.read()
changed = text != current
diff_text["before"] = current
except Exception:
changed = True
diff_text["before"] = None
if changed and not module.check_mode:
with open(path, "w") as f:
f.write(text)
file_args = module.load_file_common_arguments(module.params)
diff_attrs = {
"before_header": f"{path} (attributes)",
"after_header": f"{path} (attributes)",
}
changed = module.set_file_attributes_if_different(
file_args, changed, diff_attrs
)
return changed, [diff_text, diff_attrs]
def main() -> int:
record_types = {
@ -345,6 +380,7 @@ def main() -> int:
module = AnsibleModule(
argument_spec=module_args,
add_file_common_args=True,
supports_check_mode=True,
)
origin = dns.name.from_text(module.params["origin"])
@ -352,11 +388,6 @@ def main() -> int:
zone = dns.zone.Zone(origin)
try:
current = dns.zone.from_file(path, origin=origin)
except Exception:
current = None
records = itertools.chain(
make_records(module.params["soa"], SOA),
make_reverse_hosts_records(module.params["reverse_hosts"]),
@ -375,15 +406,11 @@ def main() -> int:
dataset = node.get_rdataset(rdata.rdclass, rdata.rdtype, create=True)
dataset.add(rdata)
file_args = module.load_file_common_arguments(module.params)
zone_text = zone.to_text(relativize=False, sorted=True)
changed = current is None or not zones_eq(zone, current)
if changed:
zone.to_file(module.params["path"], relativize=False, sorted=True)
changed, diff = write_text_file(path, zone_text, module)
changed = module.set_fs_attributes_if_different(file_args, changed)
module.exit_json(changed=changed)
module.exit_json(changed=changed, diff=diff)
return 0