Debian Codegraph @

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

raw
1 # Copyright (c) 2023-2025, 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_rfc8427
9 author:
10 - Felix Fontein (@felixfontein)
11 - Vasiliy Kiryanov (@vasiliyk)
12 short_description: Look up DNS records and return RFC 8427 JSON format
13 version_added: 3.4.0
14 requirements:
15 - dnspython >= 2.0.0
16 description:
17 - Look up DNS records and return them in L(RFC 8427 DNS message JSON format, https://www.rfc-editor.org/rfc/rfc8427.html).
18 - RFC 8427 defines a standardized format for representing DNS messages in JSON.
19 options:
20 _terms:
21 description:
22 - Domain name(s) to query.
23 type: list
24 elements: str
25 required: true
26 type:
27 description:
28 - The record type to retrieve.
29 - Support for V(HTTPS) and V(SVCB) has been added in community.dns 3.4.0.
30 type: str
31 default: A
32 choices:
33 - A
34 - AAAA
35 - CAA
36 - CNAME
37 - DNAME
38 - DNSKEY
39 - DS
40 - HINFO
41 - HTTPS
42 - LOC
43 - MX
44 - NAPTR
45 - NS
46 - NSEC
47 - NSEC3
48 - NSEC3PARAM
49 - PTR
50 - RP
51 - RRSIG
52 - SOA
53 - SPF
54 - SRV
55 - SSHFP
56 - SVCB
57 - TLSA
58 - TXT
59 query_retry:
60 description:
61 - Number of retries for DNS query timeouts.
62 type: int
63 default: 3
64 query_timeout:
65 description:
66 - Timeout per DNS query in seconds.
67 type: float
68 default: 10
69 server:
70 description:
71 - The DNS server(s) to use to look up the result. Must be a list of one or more IP addresses.
72 - By default, the system's standard resolver is used.
73 type: list
74 elements: str
75 servfail_retries:
76 description:
77 - How often to retry on SERVFAIL errors.
78 type: int
79 default: 0
80 nxdomain_handling:
81 description:
82 - How to handle NXDOMAIN errors. These appear if an unknown domain name is queried.
83 - V(empty) (default) returns an empty result for that domain name. This means that for the corresponding domain name,
84 nothing is added to RV(_result).
85 - V(fail) makes the lookup fail.
86 type: str
87 choices:
88 - empty
89 - fail
90 default: empty
91 search:
92 description:
93 - If V(false), the input is assumed to be an absolute domain name.
94 - If V(true), the input is assumed to be a relative domain name if it does not end with C(.), the search list configured
95 in the system's resolver configuration will be used for relative names, and the resolver's domain may be added to
96 relative names.
97 type: bool
98 default: true
99 notes:
100 - This plugin returns DNS messages in RFC 8427 JSON format, which includes C(Header), C(Question), C(Answer), C(Authority), and C(Additional) sections.
101 - Note that when using this lookup plugin with V(lookup(\)), and the result is a one-element list, Ansible simply returns
102 the one element not as a list. Since this behavior is surprising and can cause problems, it is better to use V(query(\))
103 instead of V(lookup(\)). See the examples and also R(Forcing lookups to return lists, query) in the Ansible documentation.
104 """
105
106 EXAMPLES = r"""
107 - name: Look up A (IPv4) records for example.org in RFC 8427 JSON format
108 ansible.builtin.debug:
109 msg: "{{ query('community.dns.lookup_rfc8427', 'example.org.') }}"
110
111 - name: Look up AAAA (IPv6) records for example.org in RFC 8427 JSON format
112 ansible.builtin.debug:
113 msg: "{{ query('community.dns.lookup_rfc8427', 'example.org.', type='AAAA' ) }}"
114
115 - name: Get complete DNS message for MX records
116 ansible.builtin.debug:
117 msg: "{{ query('community.dns.lookup_rfc8427', 'example.org.', type='MX' ) }}"
118 """
119
120 RETURN = r"""
121 _result:
122 description:
123 - DNS messages in RFC 8427 JSON format for all queried DNS names.
124 - Every element in O(_terms) corresponds to one element in this list.
125 type: list
126 elements: dict
127 sample:
128 - Header:
129 ID: 12345
130 QR: true
131 Opcode: 0
132 AA: false
133 TC: false
134 RD: true
135 RA: true
136 AD: false
137 CD: false
138 Rcode: 0
139 QDCOUNT: 1
140 ANCOUNT: 1
141 NSCOUNT: 0
142 ARCOUNT: 0
143 Question:
144 - name: example.org.
145 type: 1
146 class: 1
147 Answer:
148 - name: example.org.
149 type: 1
150 class: 1
151 TTL: 3600
152 data: 93.184.216.34
153 Authority: []
154 Additional: []
155 """
156
157 import typing as t
158
159 from ansible.errors import AnsibleLookupError
160 from ansible.module_utils.common.text.converters import to_text
161 from ansible.plugins.lookup import LookupBase
162
163 from ansible_collections.community.dns.plugins.module_utils._dnspython_records import (
164 NAME_TO_RDTYPE,
165 NAME_TO_REQUIRED_VERSION,
166 )
167 from ansible_collections.community.dns.plugins.module_utils._ips import is_ip_address
168 from ansible_collections.community.dns.plugins.module_utils._resolver import (
169 SimpleResolver,
170 )
171 from ansible_collections.community.dns.plugins.plugin_utils._resolver import (
172 assert_requirements_present as assert_requirements_present_dnspython,
173 )
174 from ansible_collections.community.dns.plugins.plugin_utils._resolver import (
175 guarded_run,
176 )
177
178 try:
179 import dns.flags
180 import dns.message
181 import dns.query
182 import dns.rcode
183 import dns.resolver
184 from dns.rdatatype import RdataType
185 from dns.resolver import NXDOMAIN
186 except ImportError:
187 # handled by assert_requirements_present_dnspython
188 pass
189
190
191 class LookupModule(LookupBase):
192 @staticmethod
193 def _convert_rrset_to_rfc8427(
194 rrset: dns.rrset.RRset,
195 ) -> list[dict[str, object]]:
196 """Convert a DNS RRset to RFC 8427 format."""
197 records = []
198 for rdata in rrset:
199 record = {
200 "name": str(rrset.name).rstrip("."), # RFC 8427: no trailing dot
201 "type": int(rrset.rdtype),
202 "class": dns.rdataclass.to_text(rrset.rdclass),
203 "ttl": rrset.ttl,
204 "data": str(rdata),
205 }
206 # For MX and similar, parse data as object if needed
207 if rrset.rdtype == dns.rdatatype.MX:
208 preference, exchange = str(rdata).split(" ", 1)
209 record["data"] = {
210 "preference": int(preference),
211 "exchange": exchange.rstrip("."),
212 }
213 records.append(record)
214 return records
215
216 @staticmethod
217 def _convert_message_to_rfc8427(
218 message: dns.message.Message, question_name: str, question_type: int
219 ) -> dict[str, object]:
220 """Convert a DNS message to RFC 8427 JSON format."""
221
222 def rrsets_to_records(rrsets: list[dns.rrset.RRset]) -> list[dict[str, object]]:
223 records: list[dict[str, object]] = []
224 for rrset in rrsets:
225 records.extend(LookupModule._convert_rrset_to_rfc8427(rrset))
226 return records
227
228 # RFC 8427 header fields
229 header = {
230 "id": message.id,
231 "flags": [
232 f for f in dns.flags.to_text(message.flags).split() if f
233 ], # list of flag strings
234 "rcode": dns.rcode.to_text(message.rcode()),
235 "question_count": len(message.question),
236 "answer_count": len(message.answer),
237 "authority_count": len(message.authority),
238 "additional_count": len(message.additional),
239 }
240
241 # RFC 8427 Question section
242 question = [
243 {
244 "name": question_name.rstrip("."),
245 "type": question_type,
246 "class": dns.rdataclass.to_text(dns.rdataclass.IN),
247 }
248 ]
249
250 result: dict[str, object] = {
251 "Header": header,
252 "Question": question,
253 "Answer": rrsets_to_records(message.answer),
254 "Authority": rrsets_to_records(message.authority),
255 "Additional": rrsets_to_records(message.additional),
256 }
257 return result
258
259 @staticmethod
260 def _resolve(
261 resolver: SimpleResolver,
262 name: str,
263 rdtype: RdataType,
264 server_addresses: list[str] | None,
265 nxdomain_handling: t.Literal["empty", "fail"],
266 target_can_be_relative: bool = True,
267 search: bool = True,
268 ) -> dict[str, t.Any]:
269 def callback() -> dict[str, t.Any]:
270 try:
271 rrset = resolver.resolve(
272 name,
273 rdtype=rdtype,
274 server_addresses=server_addresses,
275 nxdomain_is_empty=nxdomain_handling == "empty",
276 target_can_be_relative=target_can_be_relative,
277 search=search,
278 )
279 # Create a response message and append the answer
280 query = dns.message.make_query(name, rdtype)
281 response_msg = dns.message.make_response(query)
282 if rrset:
283 response_msg.answer.append(rrset)
284 return LookupModule._convert_message_to_rfc8427(
285 response_msg, name, int(rdtype)
286 )
287 except dns.resolver.NXDOMAIN:
288 raise AnsibleLookupError(f"Got NXDOMAIN when querying {name}") from None
289
290 return guarded_run(
291 callback,
292 error_class=AnsibleLookupError,
293 server=name,
294 )
295
296 @staticmethod
297 def _get_resolver(
298 resolver: SimpleResolver, server: str
299 ) -> t.Callable[[], list[str]]:
300 def f():
301 try:
302 return resolver.resolve_addresses(server)
303 except NXDOMAIN as exc:
304 raise AnsibleLookupError(
305 f"Nameserver {server} does not exist ({exc})"
306 ) from None
307
308 return f
309
310 def run(
311 self, terms: list[t.Any], variables: t.Any | None = None, **kwargs: t.Any
312 ) -> list[dict[str, t.Any]]:
313 assert_requirements_present_dnspython("community.dns.lookup_rfc8427", "lookup")
314
315 self.set_options(var_options=variables, direct=kwargs)
316
317 resolver = SimpleResolver(
318 timeout=self.get_option("query_timeout"),
319 timeout_retries=self.get_option("query_retry"),
320 servfail_retries=self.get_option("servfail_retries"),
321 )
322
323 record_type = self.get_option("type")
324 if record_type not in NAME_TO_RDTYPE:
325 min_version = NAME_TO_REQUIRED_VERSION[record_type]
326 raise AnsibleLookupError(
327 f"Your dnspython version does not support {record_type} records. You need version {min_version} or newer."
328 )
329 rdtype = NAME_TO_RDTYPE[record_type]
330
331 nxdomain_handling: t.Literal["empty", "fail"] = self.get_option(
332 "nxdomain_handling"
333 )
334
335 search: bool = self.get_option("search")
336
337 server_addresses: list[str] | None = None
338 if self.get_option("server"):
339 server_addresses = []
340 servers: list[str] = self.get_option("server")
341 for server in servers:
342 if is_ip_address(server):
343 server_addresses.append(server)
344 continue
345 server_addresses.extend(
346 guarded_run(
347 self._get_resolver(resolver, server),
348 error_class=AnsibleLookupError,
349 server=server,
350 )
351 )
352
353 result = []
354 for name in terms:
355 result.append(
356 self._resolve(
357 resolver,
358 to_text(name),
359 rdtype,
360 server_addresses,
361 nxdomain_handling,
362 target_can_be_relative=search,
363 search=search,
364 )
365 )
366 return result