Debian Codegraph @

ansible_collections/community/general/plugins/modules/ipa_dnsrecord.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Abhijeet Kasurde ([email protected])
3 #
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: ipa_dnsrecord
11 author: Abhijeet Kasurde (@Akasurde)
12 short_description: Manage FreeIPA DNS records
13 description:
14 - Add, modify and delete an IPA DNS Record using IPA API.
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 zone_name:
22 description:
23 - The DNS zone name to which DNS record needs to be managed.
24 required: true
25 type: str
26 record_name:
27 description:
28 - The DNS record name to manage.
29 required: true
30 aliases: ["name"]
31 type: str
32 record_type:
33 description:
34 - The type of DNS record name.
35 - Support for V(NS) was added in comunity.general 8.2.0.
36 - Support for V(SSHFP) was added in community.general 9.1.0.
37 default: 'A'
38 choices: ['A', 'AAAA', 'A6', 'CNAME', 'DNAME', 'MX', 'NS', 'PTR', 'SRV', 'TXT', 'SSHFP']
39 type: str
40 record_value:
41 description:
42 - Manage DNS record name with this value.
43 - Mutually exclusive with O(record_values), and exactly one of O(record_value) and O(record_values) has to be specified.
44 - Use O(record_values) if you need to specify multiple values.
45 - In the case of V(A) or V(AAAA) record types, this is the IP address.
46 - In the case of V(A6) record type, this is the A6 Record data.
47 - In the case of V(CNAME) record type, this is the hostname.
48 - In the case of V(DNAME) record type, this is the DNAME target.
49 - In the case of V(NS) record type, this is the name server hostname. Hostname must already have a valid A or AAAA record.
50 - In the case of V(PTR) record type, this is the hostname.
51 - In the case of V(TXT) record type, this is a text.
52 - In the case of V(SRV) record type, this is a service record.
53 - In the case of V(MX) record type, this is a mail exchanger record.
54 - In the case of V(SSHFP) record type, this is an SSH fingerprint record.
55 type: str
56 record_values:
57 description:
58 - Manage DNS record name with this value.
59 - Mutually exclusive with O(record_value), and exactly one of O(record_value) and O(record_values) has to be specified.
60 - In the case of V(A) or V(AAAA) record types, this is the IP address.
61 - In the case of V(A6) record type, this is the A6 Record data.
62 - In the case of V(CNAME) record type, this is the hostname.
63 - In the case of V(DNAME) record type, this is the DNAME target.
64 - In the case of V(NS) record type, this is the name server hostname. Hostname must already have a valid A or AAAA record.
65 - In the case of V(PTR) record type, this is the hostname.
66 - In the case of V(TXT) record type, this is a text.
67 - In the case of V(SRV) record type, this is a service record.
68 - In the case of V(MX) record type, this is a mail exchanger record.
69 - In the case of V(SSHFP) record type, this is an SSH fingerprint record.
70 type: list
71 elements: str
72 record_ttl:
73 description:
74 - Set the TTL for the record.
75 - Applies only when adding a new or changing the value of O(record_value) or O(record_values).
76 type: int
77 exclusive:
78 description:
79 - Whether the provided record value(s) should be the only ones for that record type and record name.
80 - When O(state=present) and V(true), the specified O(record_value) or O(record_values) will
81 replace all existing records of the same type and name.
82 - When O(state=present) and V(false), the specified values will be added to any existing records
83 of the same type and name, preserving values not listed.
84 - When O(state=absent) and V(true), all existing records of the same type and name will be removed,
85 regardless of the specified O(record_value) or O(record_values).
86 - When O(state=absent) and V(false), only the specified values will be removed from the record,
87 preserving other existing values.
88 type: bool
89 default: true
90 version_added: 12.6.0
91 state:
92 description: State to ensure.
93 default: present
94 choices: ["absent", "present"]
95 type: str
96 extends_documentation_fragment:
97 - community.general._ipa.documentation
98 - community.general._ipa.connection_notes
99 - community.general._attributes
100 """
101
102 EXAMPLES = r"""
103 - name: Ensure dns record is present
104 community.general.ipa_dnsrecord:
105 ipa_host: spider.example.com
106 ipa_pass: Passw0rd!
107 state: present
108 zone_name: example.com
109 record_name: vm-001
110 record_type: 'AAAA'
111 record_value: '::1'
112
113 - name: Ensure that dns records exists with a TTL
114 community.general.ipa_dnsrecord:
115 name: host02
116 zone_name: example.com
117 record_type: 'AAAA'
118 record_values: '::1,fe80::1'
119 record_ttl: 300
120 ipa_host: ipa.example.com
121 ipa_pass: topsecret
122 state: present
123
124 - name: Ensure a PTR record is present
125 community.general.ipa_dnsrecord:
126 ipa_host: spider.example.com
127 ipa_pass: Passw0rd!
128 state: present
129 zone_name: 2.168.192.in-addr.arpa
130 record_name: 5
131 record_type: 'PTR'
132 record_value: 'internal.ipa.example.com'
133
134 - name: Ensure a TXT record is present
135 community.general.ipa_dnsrecord:
136 ipa_host: spider.example.com
137 ipa_pass: Passw0rd!
138 state: present
139 zone_name: example.com
140 record_name: _kerberos
141 record_type: 'TXT'
142 record_value: 'EXAMPLE.COM'
143
144 - name: Ensure an SRV record is present
145 community.general.ipa_dnsrecord:
146 ipa_host: spider.example.com
147 ipa_pass: Passw0rd!
148 state: present
149 zone_name: example.com
150 record_name: _kerberos._udp.example.com
151 record_type: 'SRV'
152 record_value: '10 50 88 ipa.example.com'
153
154 - name: Ensure an MX records are present
155 community.general.ipa_dnsrecord:
156 ipa_host: spider.example.com
157 ipa_pass: Passw0rd!
158 state: present
159 zone_name: example.com
160 record_name: '@'
161 record_type: 'MX'
162 record_values:
163 - '1 mailserver-01.example.com'
164 - '2 mailserver-02.example.com'
165
166 - name: Ensure an SRV record is added without replacing existing ones
167 community.general.ipa_dnsrecord:
168 ipa_host: spider.example.com
169 ipa_pass: Passw0rd!
170 state: present
171 zone_name: example.com
172 record_name: _etcd-server-ssl._tcp.cloud.example.com.
173 record_type: 'SRV'
174 record_value: '0 10 2380 etcd-0.cloud.example.com.'
175 exclusive: false
176
177 - name: Ensure that dns record is removed
178 community.general.ipa_dnsrecord:
179 name: host01
180 zone_name: example.com
181 record_type: 'AAAA'
182 record_value: '::1'
183 ipa_host: ipa.example.com
184 ipa_user: admin
185 ipa_pass: topsecret
186 state: absent
187
188 - name: Ensure an NS record for a subdomain is present
189 community.general.ipa_dnsrecord:
190 name: subdomain
191 zone_name: example.com
192 record_type: 'NS'
193 record_value: 'ns1.subdomain.exmaple.com'
194 ipa_host: ipa.example.com
195 ipa_user: admin
196 ipa_pass: ChangeMe!
197
198 - name: Retrieve the current sshfp fingerprints
199 ansible.builtin.command: ssh-keyscan -D localhost
200 register: ssh_hostkeys
201
202 - name: Update the SSHFP records in DNS
203 community.general.ipa_dnsrecord:
204 name: "{{ inventory_hostname}}"
205 zone_name: example.com
206 record_type: 'SSHFP'
207 record_values: "{{ ssh_hostkeys.stdout.split('\n') | map('split', 'SSHFP ') | map('last') | list }}"
208 ipa_host: ipa.example.com
209 ipa_user: admin
210 ipa_pass: ChangeMe!
211 """
212
213 RETURN = r"""
214 dnsrecord:
215 description: DNS record as returned by IPA API.
216 returned: always
217 type: dict
218 """
219
220 import traceback
221
222 from ansible.module_utils.basic import AnsibleModule
223 from ansible.module_utils.common.text.converters import to_native
224
225 from ansible_collections.community.general.plugins.module_utils._ipa import IPAClient, ipa_argument_spec
226
227
228 class DNSRecordIPAClient(IPAClient):
229 def __init__(self, module, host, port, protocol):
230 super().__init__(module, host, port, protocol)
231
232 def dnsrecord_find(self, zone_name, record_name):
233 if record_name == "@":
234 method = "dnsrecord_show"
235 else:
236 method = "dnsrecord_find"
237 result = self._post_json(method=method, name=zone_name, item={"idnsname": record_name, "all": True})
238 if "dnsttl" in result:
239 result["dnsttl"] = [int(v) for v in result["dnsttl"]]
240 return result
241
242 def dnsrecord_add(self, zone_name=None, record_name=None, details=None):
243 item = dict(idnsname=record_name)
244
245 if details.get("record_ttl"):
246 item.update(dnsttl=details["record_ttl"])
247
248 for value in details["record_values"]:
249 if details["record_type"] == "A":
250 item.update(a_part_ip_address=value)
251 elif details["record_type"] == "AAAA":
252 item.update(aaaa_part_ip_address=value)
253 elif details["record_type"] == "A6":
254 item.update(a6_part_data=value)
255 elif details["record_type"] == "CNAME":
256 item.update(cname_part_hostname=value)
257 elif details["record_type"] == "DNAME":
258 item.update(dname_part_target=value)
259 elif details["record_type"] == "NS":
260 item.update(ns_part_hostname=value)
261 elif details["record_type"] == "PTR":
262 item.update(ptr_part_hostname=value)
263 elif details["record_type"] == "TXT":
264 item.update(txtrecord=value)
265 elif details["record_type"] == "SRV":
266 item.update(srvrecord=value)
267 elif details["record_type"] == "MX":
268 item.update(mxrecord=value)
269 elif details["record_type"] == "SSHFP":
270 item.update(sshfprecord=value)
271
272 self._post_json(method="dnsrecord_add", name=zone_name, item=item)
273
274 def dnsrecord_mod(self, zone_name=None, record_name=None, details=None):
275 item = get_dnsrecord_dict(details)
276 item.update(idnsname=record_name)
277 if details.get("record_ttl"):
278 item.update(dnsttl=details["record_ttl"])
279 return self._post_json(method="dnsrecord_mod", name=zone_name, item=item)
280
281 def dnsrecord_del(self, zone_name=None, record_name=None, details=None):
282 item = get_dnsrecord_dict(details)
283 item.update(idnsname=record_name)
284 return self._post_json(method="dnsrecord_del", name=zone_name, item=item)
285
286
287 RECORD_TYPE_KEY = {
288 "A": "arecord",
289 "AAAA": "aaaarecord",
290 "A6": "a6record",
291 "CNAME": "cnamerecord",
292 "DNAME": "dnamerecord",
293 "NS": "nsrecord",
294 "PTR": "ptrrecord",
295 "TXT": "txtrecord",
296 "SRV": "srvrecord",
297 "MX": "mxrecord",
298 "SSHFP": "sshfprecord",
299 }
300
301
302 def get_dnsrecord_dict(details=None):
303 module_dnsrecord = dict()
304 if details["record_type"] == "A" and details["record_values"]:
305 module_dnsrecord.update(arecord=details["record_values"])
306 elif details["record_type"] == "AAAA" and details["record_values"]:
307 module_dnsrecord.update(aaaarecord=details["record_values"])
308 elif details["record_type"] == "A6" and details["record_values"]:
309 module_dnsrecord.update(a6record=details["record_values"])
310 elif details["record_type"] == "CNAME" and details["record_values"]:
311 module_dnsrecord.update(cnamerecord=details["record_values"])
312 elif details["record_type"] == "DNAME" and details["record_values"]:
313 module_dnsrecord.update(dnamerecord=details["record_values"])
314 elif details["record_type"] == "NS" and details["record_values"]:
315 module_dnsrecord.update(nsrecord=details["record_values"])
316 elif details["record_type"] == "PTR" and details["record_values"]:
317 module_dnsrecord.update(ptrrecord=details["record_values"])
318 elif details["record_type"] == "TXT" and details["record_values"]:
319 module_dnsrecord.update(txtrecord=details["record_values"])
320 elif details["record_type"] == "SRV" and details["record_values"]:
321 module_dnsrecord.update(srvrecord=details["record_values"])
322 elif details["record_type"] == "MX" and details["record_values"]:
323 module_dnsrecord.update(mxrecord=details["record_values"])
324 elif details["record_type"] == "SSHFP" and details["record_values"]:
325 module_dnsrecord.update(sshfprecord=details["record_values"])
326
327 if details.get("record_ttl"):
328 module_dnsrecord.update(dnsttl=details["record_ttl"])
329
330 return module_dnsrecord
331
332
333 def get_dnsrecord_diff(client, ipa_dnsrecord, module_dnsrecord):
334 details = get_dnsrecord_dict(module_dnsrecord)
335 return client.get_diff(ipa_data=ipa_dnsrecord, module_data=details)
336
337
338 def ensure(module, client):
339 zone_name = module.params["zone_name"]
340 record_name = module.params["record_name"]
341 record_ttl = module.params.get("record_ttl")
342 state = module.params["state"]
343 exclusive = module.params["exclusive"]
344
345 ipa_dnsrecord = client.dnsrecord_find(zone_name, record_name)
346
347 record_values = module.params["record_values"]
348 if module.params["record_value"] is not None:
349 record_values = [module.params["record_value"]]
350
351 module_dnsrecord = dict(
352 record_type=module.params["record_type"],
353 record_values=record_values,
354 record_ttl=to_native(record_ttl, nonstring="passthru"),
355 )
356
357 # ttl is not required to change records
358 if module_dnsrecord["record_ttl"] is None:
359 module_dnsrecord.pop("record_ttl")
360
361 changed = False
362 if state == "present":
363 if not ipa_dnsrecord:
364 changed = True
365 if not module.check_mode:
366 client.dnsrecord_add(zone_name=zone_name, record_name=record_name, details=module_dnsrecord)
367 elif exclusive:
368 diff = get_dnsrecord_diff(client, ipa_dnsrecord, module_dnsrecord)
369 if len(diff) > 0:
370 changed = True
371 if not module.check_mode:
372 client.dnsrecord_mod(zone_name=zone_name, record_name=record_name, details=module_dnsrecord)
373 else:
374 record_key = RECORD_TYPE_KEY.get(module_dnsrecord["record_type"])
375 current_values = ipa_dnsrecord.get(record_key, []) if record_key else []
376 missing_values = [v for v in record_values if v not in current_values]
377 if missing_values:
378 changed = True
379 if not module.check_mode:
380 add_details = dict(module_dnsrecord, record_values=missing_values)
381 client.dnsrecord_add(zone_name=zone_name, record_name=record_name, details=add_details)
382 else:
383 record_key = RECORD_TYPE_KEY.get(module_dnsrecord["record_type"])
384 current_values = ipa_dnsrecord.get(record_key, []) if (ipa_dnsrecord and record_key) else []
385 if exclusive:
386 if current_values:
387 changed = True
388 if not module.check_mode:
389 del_details = dict(module_dnsrecord, record_values=current_values)
390 client.dnsrecord_del(zone_name=zone_name, record_name=record_name, details=del_details)
391 else:
392 values_to_remove = [v for v in record_values if v in current_values]
393 if values_to_remove:
394 changed = True
395 if not module.check_mode:
396 del_details = dict(module_dnsrecord, record_values=values_to_remove)
397 client.dnsrecord_del(zone_name=zone_name, record_name=record_name, details=del_details)
398
399 return changed, client.dnsrecord_find(zone_name, record_name)
400
401
402 def main():
403 record_types = ["A", "AAAA", "A6", "CNAME", "DNAME", "NS", "PTR", "TXT", "SRV", "MX", "SSHFP"]
404 argument_spec = ipa_argument_spec()
405 argument_spec.update(
406 zone_name=dict(type="str", required=True),
407 record_name=dict(type="str", aliases=["name"], required=True),
408 record_type=dict(type="str", default="A", choices=record_types),
409 record_value=dict(type="str"),
410 record_values=dict(type="list", elements="str"),
411 state=dict(type="str", default="present", choices=["present", "absent"]),
412 record_ttl=dict(type="int"),
413 exclusive=dict(type="bool", default=True),
414 )
415
416 module = AnsibleModule(
417 argument_spec=argument_spec,
418 mutually_exclusive=[["record_value", "record_values"]],
419 required_one_of=[["record_value", "record_values"]],
420 supports_check_mode=True,
421 )
422
423 client = DNSRecordIPAClient(
424 module=module,
425 host=module.params["ipa_host"],
426 port=module.params["ipa_port"],
427 protocol=module.params["ipa_prot"],
428 )
429
430 try:
431 client.login(username=module.params["ipa_user"], password=module.params["ipa_pass"])
432 changed, record = ensure(module, client)
433 module.exit_json(changed=changed, record=record)
434 except Exception as e:
435 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
436
437
438 if __name__ == "__main__":
439 main()