Debian Codegraph @

ansible_collections/community/dns/plugins/lookup/lookup_as_dict.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: lookup_as_dict
9 author: Felix Fontein (@felixfontein)
10 short_description: Look up DNS records as dictionaries
11 version_added: 2.6.0
12 requirements:
13 - dnspython >= 2.0.0
14 description:
15 - Look up DNS records and return them as interpreted dictionaries.
16 options:
17 _terms:
18 description:
19 - Domain name(s) to query.
20 type: list
21 elements: str
22 required: true
23 type:
24 description:
25 - The record type to retrieve.
26 - Support for V(HTTPS) and V(SVCB) has been added in community.dns 3.4.0.
27 type: str
28 default: A
29 choices:
30 - A
31 - AAAA
32 - CAA
33 - CNAME
34 - DNAME
35 - DNSKEY
36 - DS
37 - HINFO
38 - HTTPS
39 - LOC
40 - MX
41 - NAPTR
42 - NS
43 - NSEC
44 - NSEC3
45 - NSEC3PARAM
46 - PTR
47 - RP
48 - RRSIG
49 - SOA
50 - SPF
51 - SRV
52 - SSHFP
53 - SVCB
54 - TLSA
55 - TXT
56 query_retry:
57 description:
58 - Number of retries for DNS query timeouts.
59 type: int
60 default: 3
61 query_timeout:
62 description:
63 - Timeout per DNS query in seconds.
64 type: float
65 default: 10
66 server:
67 description:
68 - The DNS server(s) to use to look up the result. Must be a list of one or more IP addresses.
69 - By default, the system's standard resolver is used.
70 type: list
71 elements: str
72 servfail_retries:
73 description:
74 - How often to retry on SERVFAIL errors.
75 type: int
76 default: 0
77 nxdomain_handling:
78 description:
79 - How to handle NXDOMAIN errors. These appear if an unknown domain name is queried.
80 - V(empty) (default) returns an empty result for that domain name. This means that for the corresponding domain name,
81 nothing is added to RV(_result).
82 - V(fail) makes the lookup fail.
83 type: str
84 choices:
85 - empty
86 - fail
87 default: empty
88 search:
89 description:
90 - If V(false), the input is assumed to be an absolute domain name.
91 - If V(true), the input is assumed to be a relative domain name if it does not end with C(.), the search list configured
92 in the system's resolver configuration will be used for relative names, and the resolver's domain may be added to
93 relative names.
94 - Note that this behavior changed in community.dns 3.0.0. In community.dns 2.x.y, O(search=false) was the only available
95 choice.
96 type: bool
97 default: true
98 version_added: 3.0.0
99 notes:
100 - Note that when using this lookup plugin with V(lookup(\)), and the result is a one-element list, Ansible simply returns
101 the one element not as a list. Since this behavior is surprising and can cause problems, it is better to use V(query(\))
102 instead of V(lookup(\)). See the examples and also R(Forcing lookups to return lists, query) in the Ansible documentation.
103 """
104
105 EXAMPLES = r"""
106 - name: Look up A (IPv4) records for example.org as a list of dictionaries
107 ansible.builtin.debug:
108 msg: "{{ query('community.dns.lookup_as_dict', 'example.org.') }}"
109
110 - name: Look up AAAA (IPv6) records for example.org as a list of IPv6 addresses
111 ansible.builtin.debug:
112 msg: "{{ query('community.dns.lookup_as_dict', 'example.org.', type='AAAA' ) | map(attribute='address') }}"
113
114 - name: Look up TXT records for ansible.com as a list of strings
115 ansible.builtin.debug:
116 msg: "{{ query('community.dns.lookup_as_dict', 'ansible.com.', type='TXT' ) | map(attribute='value') }}"
117 """
118
119 RETURN = r"""
120 _result:
121 description:
122 - The records of type O(type) for all queried DNS names.
123 - If multiple DNS names are queried in O(_terms), the resulting lists have been concatenated.
124 - Depending on O(type), different fields are returned.
125 - For O(type=TXT) and O(type=SPF), also the concatenated value is returned as RV(_result[].value).
126 type: list
127 elements: dict
128 sample:
129 - address: 127.0.0.1
130 contains:
131 address:
132 description:
133 - A IPv4 respectively IPv6 address.
134 type: str
135 returned: if O(type=A) or O(type=AAAA)
136 algorithm:
137 description:
138 - The algorithm ID.
139 type: int
140 returned: if O(type=DNSKEY) or O(type=DS) or O(type=NSEC3) or O(type=NSEC3PARAM) or O(type=RRSIG) or O(type=SSHFP)
141 altitude:
142 description:
143 - The altitude.
144 type: float
145 returned: if O(type=LOC)
146 cert:
147 description:
148 - The certificate.
149 type: str
150 returned: if O(type=TLSA)
151 cpu:
152 description:
153 - The CPU.
154 type: str
155 returned: if O(type=HINFO)
156 digest:
157 description:
158 - The digest.
159 type: str
160 returned: if O(type=DS)
161 digest_type:
162 description:
163 - The digest's type.
164 type: int
165 returned: if O(type=DS)
166 exchange:
167 description:
168 - The exchange server.
169 type: str
170 returned: if O(type=MX)
171 expiration:
172 description:
173 - The expiration Unix timestamp.
174 type: int
175 returned: if O(type=RRSIG)
176 expire:
177 description:
178 - Number of seconds after which secondary name servers should stop answering request for this zone if the main name
179 server does not respond.
180 type: int
181 returned: if O(type=SOA)
182 fingerprint:
183 description:
184 - The fingerprint.
185 type: str
186 returned: if O(type=SSHFP)
187 flags:
188 description:
189 - Flags.
190 - This is actually of type C(string) for O(type=NAPTR).
191 type: int
192 returned: if O(type=CAA) or O(type=DNSKEY) or O(type=NAPTR) or O(type=NSEC3) or O(type=NSEC3PARAM)
193 fp_type:
194 description:
195 - The fingerprint's type.
196 type: int
197 returned: if O(type=SSHFP)
198 horizontal_precision:
199 description:
200 - The horizontal precision of the location.
201 type: float
202 returned: if O(type=LOC)
203 inception:
204 description:
205 - The inception Unix timestamp.
206 type: int
207 returned: if O(type=RRSIG)
208 iterations:
209 description:
210 - The number of iterations.
211 type: int
212 returned: if O(type=NSEC3) or O(type=NSEC3PARAM)
213 key:
214 description:
215 - The key.
216 type: str
217 returned: if O(type=DNSKEY)
218 key_tag:
219 description:
220 - The key's tag.
221 type: int
222 returned: if O(type=DS) or O(type=RRSIG)
223 labels:
224 description:
225 - The labels.
226 type: int
227 returned: if O(type=RRSIG)
228 latitude:
229 description:
230 - The location's latitude.
231 type: list
232 elements: int
233 returned: if O(type=LOC)
234 longitude:
235 description:
236 - The location's longitude.
237 type: list
238 elements: int
239 returned: if O(type=LOC)
240 mbox:
241 description:
242 - The mbox.
243 type: str
244 returned: if O(type=RP)
245 minimum:
246 description:
247 - Used to calculate the TTL for purposes of negative caching.
248 type: int
249 returned: if O(type=SOA)
250 mname:
251 description:
252 - Primary main name server for this zone.
253 type: str
254 returned: if O(type=SOA)
255 mtype:
256 description:
257 - The mtype.
258 type: int
259 returned: if O(type=TLSA)
260 next:
261 description:
262 - The next value.
263 type: str
264 returned: if O(type=NSEC) or O(type=NSEC3)
265 order:
266 description:
267 - The order value.
268 type: int
269 returned: if O(type=NAPTR)
270 original_ttl:
271 description:
272 - The original TTL.
273 type: int
274 returned: if O(type=RRSIG)
275 os:
276 description:
277 - The operating system.
278 type: str
279 returned: if O(type=HINFO)
280 params:
281 description:
282 - The parameters. See L(RFC 9460, https://datatracker.ietf.org/doc/rfc9460/?include_text=1) for details.
283 type: dict
284 returned: if O(type=HTTPS) or O(type=SVCB)
285 contains:
286 mandatory:
287 description:
288 - Keys of parameters that are considered mandatory.
289 type: list
290 elements: str
291 alpn:
292 description:
293 - List of Base64-encoded ALPN IDs.
294 type: list
295 elements: str
296 no-default-alpn:
297 description:
298 - The value will always be V(null) if this key is present.
299 type: raw
300 port:
301 description:
302 - A port.
303 type: int
304 ipv4hint:
305 description:
306 - A list of IPv4 addresses.
307 type: list
308 elements: str
309 ech:
310 description:
311 - A Base64-encoded ECH (Encrypted Client Hello) key.
312 type: raw
313 ipv6hint:
314 description:
315 - A list of IPv6 addresses.
316 type: list
317 elements: str
318 ohttp:
319 description:
320 - The value will always be V(null) if this key is present.
321 type: raw
322 port:
323 description:
324 - The port.
325 type: int
326 returned: if O(type=SRV)
327 preference:
328 description:
329 - The preference value for this record.
330 type: int
331 returned: if O(type=MX) or O(type=NAPTR)
332 priority:
333 description:
334 - The priority value for this record.
335 type: int
336 returned: if O(type=HTTPS), O(type=SRV), or O(type=SVCB)
337 protocol:
338 description:
339 - The protocol.
340 type: int
341 returned: if O(type=DNSKEY)
342 refresh:
343 description:
344 - Number of seconds after which secondary name servers should query the main name server for the SOA record to detect
345 zone changes.
346 type: int
347 returned: if O(type=SOA)
348 regexp:
349 description:
350 - A regular expression.
351 type: str
352 returned: if O(type=NAPTR)
353 replacement:
354 description:
355 - The replacement.
356 type: str
357 returned: if O(type=NAPTR)
358 retry:
359 description:
360 - Number of seconds after which secondary name servers should retry to request the serial number from the main name
361 server if the main name server does not respond.
362 type: int
363 returned: if O(type=SOA)
364 rname:
365 description:
366 - E-mail address of the administrator responsible for this zone.
367 type: str
368 returned: if O(type=SOA)
369 salt:
370 description:
371 - The salt.
372 type: str
373 returned: if O(type=NSEC3) or O(type=NSEC3PARAM)
374 selector:
375 description:
376 - The selector.
377 type: int
378 returned: if O(type=TLSA)
379 serial:
380 description:
381 - Serial number for this zone.
382 type: int
383 returned: if O(type=SOA)
384 service:
385 description:
386 - The service.
387 type: str
388 returned: if O(type=NAPTR)
389 signature:
390 description:
391 - The signature.
392 type: str
393 returned: if O(type=RRSIG)
394 signer:
395 description:
396 - The signer.
397 type: str
398 returned: if O(type=RRSIG)
399 size:
400 description:
401 - The size of the location.
402 type: float
403 returned: if O(type=LOC)
404 strings:
405 description:
406 - List of strings for this record.
407 - See RV(_result[].value) for the concatenated result.
408 type: list
409 elements: str
410 returned: if O(type=SPF) or O(type=TXT)
411 tag:
412 description:
413 - The tag.
414 type: str
415 returned: if O(type=CAA)
416 target:
417 description:
418 - The target.
419 type: str
420 returned: if O(type=CNAME), O(type=DNAME), O(type=HTTPS), O(type=NS), O(type=PTR), O(type=SRV), or O(type=SVCB)
421 txt:
422 description:
423 - The TXT value.
424 type: str
425 returned: if O(type=RP)
426 type_covered:
427 description:
428 - The type covered.
429 type: str
430 returned: if O(type=RRSIG)
431 usage:
432 description:
433 - The usage flag.
434 type: int
435 returned: if O(type=TLSA)
436 value:
437 description:
438 - The value.
439 - For O(type=SPF) or O(type=TXT), this is the concatenation of RV(_result[].strings).
440 type: str
441 returned: if O(type=CAA) or O(type=SPF) or O(type=TXT)
442 vertical_precision:
443 description:
444 - The vertical precision of the location.
445 type: float
446 returned: if O(type=LOC)
447 weight:
448 description:
449 - The service's weight.
450 type: int
451 returned: if O(type=SRV)
452 windows:
453 description:
454 - The windows.
455 type: str
456 returned: if O(type=NSEC) or O(type=NSEC3)
457 """
458
459 import typing as t
460 from collections.abc import Callable
461
462 from ansible.errors import AnsibleLookupError
463 from ansible.module_utils.common.text.converters import to_text
464 from ansible.plugins.lookup import LookupBase
465
466 from ansible_collections.community.dns.plugins.module_utils._dnspython_records import (
467 NAME_TO_RDTYPE,
468 NAME_TO_REQUIRED_VERSION,
469 convert_rdata_to_dict,
470 )
471 from ansible_collections.community.dns.plugins.module_utils._ips import is_ip_address
472 from ansible_collections.community.dns.plugins.module_utils._resolver import (
473 SimpleResolver,
474 )
475 from ansible_collections.community.dns.plugins.plugin_utils._resolver import (
476 assert_requirements_present as assert_requirements_present_dnspython,
477 )
478 from ansible_collections.community.dns.plugins.plugin_utils._resolver import (
479 guarded_run,
480 )
481
482 try:
483 import dns.resolver
484 from dns.rdatatype import RdataType
485 from dns.resolver import NXDOMAIN
486 except ImportError:
487 # handled by assert_requirements_present_dnspython
488 pass
489 else:
490 RdataType = int # type: ignore # noqa: F811
491
492
493 class LookupModule(LookupBase):
494 @staticmethod
495 def _resolve(
496 resolver: SimpleResolver,
497 name: str,
498 rdtype: RdataType,
499 server_addresses: list[str] | None,
500 nxdomain_handling: t.Literal["empty", "fail"],
501 target_can_be_relative: bool = True,
502 search: bool = True,
503 ) -> list[dict[str, t.Any]]:
504 def callback() -> list[dict[str, t.Any]]:
505 try:
506 rrset = resolver.resolve(
507 name,
508 rdtype=rdtype,
509 server_addresses=server_addresses,
510 nxdomain_is_empty=nxdomain_handling == "empty",
511 target_can_be_relative=target_can_be_relative,
512 search=search,
513 )
514 if not rrset:
515 return []
516 return [convert_rdata_to_dict(data) for data in rrset]
517 except dns.resolver.NXDOMAIN:
518 raise AnsibleLookupError(f"Got NXDOMAIN when querying {name}") from None
519
520 return guarded_run(
521 callback,
522 error_class=AnsibleLookupError,
523 server=name,
524 )
525
526 @staticmethod
527 def _get_resolver(resolver: SimpleResolver, server: str) -> Callable[[], list[str]]:
528 def f():
529 try:
530 return resolver.resolve_addresses(server)
531 except NXDOMAIN as exc:
532 raise AnsibleLookupError(
533 f"Nameserver {server} does not exist ({exc})"
534 ) from None
535
536 return f
537
538 def run(
539 self, terms: list[t.Any], variables: t.Any | None = None, **kwargs: t.Any
540 ) -> list[dict[str, t.Any]]:
541 assert_requirements_present_dnspython("community.dns.lookup", "lookup_as_dict")
542
543 self.set_options(var_options=variables, direct=kwargs)
544
545 resolver = SimpleResolver(
546 timeout=self.get_option("query_timeout"),
547 timeout_retries=self.get_option("query_retry"),
548 servfail_retries=self.get_option("servfail_retries"),
549 )
550
551 record_type = self.get_option("type")
552 if record_type not in NAME_TO_RDTYPE:
553 min_version = NAME_TO_REQUIRED_VERSION[record_type]
554 raise AnsibleLookupError(
555 f"Your dnspython version does not support {record_type} records. You need version {min_version} or newer."
556 )
557 rdtype = NAME_TO_RDTYPE[record_type]
558
559 nxdomain_handling: t.Literal["empty", "fail"] = self.get_option(
560 "nxdomain_handling"
561 )
562
563 search: bool = self.get_option("search")
564
565 server_addresses: list[str] | None = None
566 if self.get_option("server"):
567 server_addresses = []
568 servers: list[str] = self.get_option("server")
569 for server in servers:
570 if is_ip_address(server):
571 server_addresses.append(server)
572 continue
573 server_addresses.extend(
574 guarded_run(
575 self._get_resolver(resolver, server),
576 error_class=AnsibleLookupError,
577 server=server,
578 )
579 )
580
581 result = []
582 for name in terms:
583 result.extend(
584 self._resolve(
585 resolver,
586 to_text(name),
587 rdtype,
588 server_addresses,
589 nxdomain_handling,
590 target_can_be_relative=search,
591 search=search,
592 )
593 )
594 return result