Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Red Hat, Inc.
4 # Copyright (c) 2014, Tim Bielawa <[email protected]>
5 # Copyright (c) 2014, Magnus Hedemark <[email protected]>
6 # Copyright (c) 2017, Dag Wieers <[email protected]>
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: xml
14 short_description: Manage bits and pieces of XML files or strings
15 description:
16 - A CRUD-like interface to managing bits of XML files.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: full
24 options:
25 path:
26 description:
27 - Path to the file to operate on.
28 - This file must exist ahead of time.
29 - This parameter is required, unless O(xmlstring) is given.
30 type: path
31 aliases: [dest, file]
32 xmlstring:
33 description:
34 - A string containing XML on which to operate.
35 - This parameter is required, unless O(path) is given.
36 type: str
37 xpath:
38 description:
39 - A valid XPath expression describing the item(s) you want to manipulate.
40 - Operates on the document root, V(/), by default.
41 type: str
42 namespaces:
43 description:
44 - The namespace C(prefix:uri) mapping for the XPath expression.
45 - Needs to be a C(dict), not a C(list) of items.
46 type: dict
47 default: {}
48 state:
49 description:
50 - Set or remove an xpath selection (node(s), attribute(s)).
51 type: str
52 choices: [absent, present]
53 default: present
54 aliases: [ensure]
55 attribute:
56 description:
57 - The attribute to select when using parameter O(value).
58 - This is a string, not prepended with V(@).
59 type: raw
60 value:
61 description:
62 - Desired state of the selected attribute.
63 - Either a string, or to unset a value, the Python V(None) keyword (YAML Equivalent, V(null)).
64 - Elements default to no value (but present).
65 - Attributes default to an empty string.
66 type: raw
67 add_children:
68 description:
69 - Add additional child-element(s) to a selected element for a given O(xpath).
70 - Child elements must be given in a list and each item may be either a string (for example C(children=ansible) to add
71 an empty C(<ansible/>) child element), or a hash where the key is an element name and the value is the element value.
72 - This parameter requires O(xpath) to be set.
73 type: list
74 elements: raw
75 set_children:
76 description:
77 - Set the child-element(s) of a selected element for a given O(xpath).
78 - Removes any existing children.
79 - Child elements must be specified as in O(add_children).
80 - This parameter requires O(xpath) to be set.
81 type: list
82 elements: raw
83 count:
84 description:
85 - Search for a given O(xpath) and provide the count of any matches.
86 - This parameter requires O(xpath) to be set.
87 type: bool
88 default: false
89 print_match:
90 description:
91 - Search for a given O(xpath) and print out any matches.
92 - This parameter requires O(xpath) to be set.
93 type: bool
94 default: false
95 pretty_print:
96 description:
97 - Pretty print XML output.
98 type: bool
99 default: false
100 content:
101 description:
102 - Search for a given O(xpath) and get content.
103 - This parameter requires O(xpath) to be set.
104 type: str
105 choices: [attribute, text]
106 input_type:
107 description:
108 - Type of input for O(add_children) and O(set_children).
109 type: str
110 choices: [xml, yaml]
111 default: yaml
112 backup:
113 description:
114 - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered
115 it incorrectly.
116 type: bool
117 default: false
118 strip_cdata_tags:
119 description:
120 - Remove CDATA tags surrounding text values.
121 - Note that this might break your XML file if text values contain characters that could be interpreted as XML.
122 type: bool
123 default: false
124 huge_tree:
125 description:
126 - Disable libxml2 security restrictions on XML node size or document depth, allowing processing of very large XML files.
127 - This option should only be activated when needed, as it disables internal safety limits.
128 type: bool
129 default: false
130 version_added: "13.0.0"
131 insertbefore:
132 description:
133 - Add additional child-element(s) before the first selected element for a given O(xpath).
134 - Child elements must be given in a list and each item may be either a string (for example C(children=ansible) to add
135 an empty C(<ansible/>) child element), or a hash where the key is an element name and the value is the element value.
136 - This parameter requires O(xpath) to be set.
137 type: bool
138 default: false
139 insertafter:
140 description:
141 - Add additional child-element(s) after the last selected element for a given O(xpath).
142 - Child elements must be given in a list and each item may be either a string (for example C(children=ansible) to add
143 an empty C(<ansible/>) child element), or a hash where the key is an element name and the value is the element value.
144 - This parameter requires O(xpath) to be set.
145 type: bool
146 default: false
147 create_if_missing:
148 description:
149 - When using O(value) and the O(xpath) matches no nodes, create the node.
150 - When set to V(false), a no-match is silently ignored instead of creating a new node.
151 type: bool
152 default: true
153 version_added: "13.0.0"
154 requirements:
155 - lxml >= 2.3.0
156 notes:
157 - Use the C(--check) and C(--diff) options when testing your expressions.
158 - The diff output is automatically pretty-printed, so may not reflect the actual file content, only the file structure.
159 - This module does not handle complicated xpath expressions, so limit xpath selectors to simple expressions.
160 - Beware that in case your XML elements are namespaced, you need to use the O(namespaces) parameter, see the examples.
161 - Namespaces prefix should be used for all children of an element where namespace is defined, unless another namespace is
162 defined for them.
163 seealso:
164 - name: XML module development community wiki (archived)
165 description: More information related to the development of this xml module.
166 link: https://github.com/ansible/community/wiki/Module:-xml
167 - name: Introduction to XPath
168 description: A brief tutorial on XPath (w3schools.com).
169 link: https://www.w3schools.com/xml/xpath_intro.asp
170 - name: XPath Reference document
171 description: The reference documentation on XSLT/XPath (developer.mozilla.org).
172 link: https://developer.mozilla.org/en-US/docs/Web/XPath
173 author:
174 - Tim Bielawa (@tbielawa)
175 - Magnus Hedemark (@magnus919)
176 - Dag Wieers (@dagwieers)
177 """
178
179 EXAMPLES = r"""
180 # Consider the following XML file:
181 #
182 # <business type="bar">
183 # <name>Tasty Beverage Co.</name>
184 # <beers>
185 # <beer>Rochefort 10</beer>
186 # <beer>St. Bernardus Abbot 12</beer>
187 # <beer>Schlitz</beer>
188 # </beers>
189 # <rating subjective="true">10</rating>
190 # <website>
191 # <mobilefriendly/>
192 # <address>http://tastybeverageco.com</address>
193 # </website>
194 # </business>
195
196 - name: Remove the 'subjective' attribute of the 'rating' element
197 community.general.xml:
198 path: /foo/bar.xml
199 xpath: /business/rating/@subjective
200 state: absent
201
202 - name: Set the rating to '11'
203 community.general.xml:
204 path: /foo/bar.xml
205 xpath: /business/rating
206 value: "11" # must quote to ensure it is parsed as string
207
208 # Retrieve and display the number of nodes
209 - name: Get count of 'beers' nodes
210 community.general.xml:
211 path: /foo/bar.xml
212 xpath: /business/beers/beer
213 count: true
214 register: hits
215
216 - ansible.builtin.debug:
217 var: hits.count
218
219 # Example where parent XML nodes are created automatically
220 - name: Add a 'phonenumber' element to the 'business' element
221 community.general.xml:
222 path: /foo/bar.xml
223 xpath: /business/phonenumber
224 value: 555-555-1234
225
226 - name: Add several more beers to the 'beers' element
227 community.general.xml:
228 path: /foo/bar.xml
229 xpath: /business/beers
230 add_children:
231 - beer: Old Rasputin
232 - beer: Old Motor Oil
233 - beer: Old Curmudgeon
234
235 - name: Add several more beers to the 'beers' element and add them before the 'Rochefort 10' element
236 community.general.xml:
237 path: /foo/bar.xml
238 xpath: '/business/beers/beer[text()="Rochefort 10"]'
239 insertbefore: true
240 add_children:
241 - beer: Old Rasputin
242 - beer: Old Motor Oil
243 - beer: Old Curmudgeon
244
245 # NOTE: The 'state' defaults to 'present' and 'value' defaults to 'null' for elements
246 - name: Add a 'validxhtml' element to the 'website' element
247 community.general.xml:
248 path: /foo/bar.xml
249 xpath: /business/website/validxhtml
250
251 - name: Add an empty 'validatedon' attribute to the 'validxhtml' element
252 community.general.xml:
253 path: /foo/bar.xml
254 xpath: /business/website/validxhtml/@validatedon
255
256 - name: Add or modify an attribute, add element if needed
257 community.general.xml:
258 path: /foo/bar.xml
259 xpath: /business/website/validxhtml
260 attribute: validatedon
261 value: 1976-08-05
262
263 # How to read an attribute value and access it in Ansible
264 - name: Read an element's attribute values
265 community.general.xml:
266 path: /foo/bar.xml
267 xpath: /business/website/validxhtml
268 content: attribute
269 register: xmlresp
270
271 - name: Show an attribute value
272 ansible.builtin.debug:
273 var: xmlresp.matches[0].validxhtml.validatedon
274
275 - name: Remove all children from the 'website' element (option 1)
276 community.general.xml:
277 path: /foo/bar.xml
278 xpath: /business/website/*
279 state: absent
280
281 - name: Remove all children from the 'website' element (option 2)
282 community.general.xml:
283 path: /foo/bar.xml
284 xpath: /business/website
285 set_children: []
286
287 # In case of namespaces, like in below XML, they have to be explicitly stated.
288 #
289 # <foo xmlns="http://x.test" xmlns:attr="http://z.test">
290 # <bar>
291 # <baz xmlns="http://y.test" attr:my_namespaced_attribute="true" />
292 # </bar>
293 # </foo>
294
295 # NOTE: There is the prefix 'x' in front of the 'bar' element, too.
296 - name: Set namespaced '/x:foo/x:bar/y:baz/@z:my_namespaced_attribute' to 'false'
297 community.general.xml:
298 path: foo.xml
299 xpath: /x:foo/x:bar/y:baz
300 namespaces:
301 x: http://x.test
302 y: http://y.test
303 z: http://z.test
304 attribute: z:my_namespaced_attribute
305 value: 'false'
306
307 - name: Adding building nodes with floor subnodes from a YAML variable
308 community.general.xml:
309 path: /foo/bar.xml
310 xpath: /business
311 add_children:
312 - building:
313 # Attributes
314 name: Scumm bar
315 location: Monkey island
316 # Value
317 +value: unreal
318 # Subnodes
319 _:
320 - floor: Pirate hall
321 - floor: Grog storage
322 - construction_date: "1990" # Only strings are valid
323 - building: Grog factory
324
325 # Consider this XML for following example -
326 #
327 # <config>
328 # <element name="test1">
329 # <text>part to remove</text>
330 # </element>
331 # <element name="test2">
332 # <text>part to keep</text>
333 # </element>
334 # </config>
335
336 - name: Delete element node based upon attribute
337 community.general.xml:
338 path: bar.xml
339 xpath: /config/element[@name='test1']
340 state: absent
341 """
342
343 RETURN = r"""
344 actions:
345 description: A dictionary with the original xpath, namespaces and state.
346 type: dict
347 returned: success
348 sample:
349 {
350 "xpath": "xpath",
351 "namespaces": [
352 "namespace1",
353 "namespace2"
354 ],
355 "state": "present"
356 }
357 count:
358 description: The count of xpath matches.
359 type: int
360 returned: when parameter O(count) is set
361 sample: 2
362 matches:
363 description: The xpath matches found.
364 type: list
365 returned: when parameter O(print_match) is set, or when parameter O(content) is set
366 xmlstring:
367 description: An XML string of the resulting output.
368 type: str
369 returned: when parameter O(xmlstring) is set
370 """
371
372 import copy
373 import json
374 import os
375 import re
376 import traceback
377 from collections.abc import MutableMapping
378 from io import BytesIO
379
380 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
381
382 LXML_IMP_ERR = None
383 try:
384 from lxml import etree, objectify
385
386 LXML_VERSION_STR = ".".join(str(f) for f in etree.LXML_VERSION)
387 HAS_LXML = True
388 except ImportError:
389 LXML_IMP_ERR = traceback.format_exc()
390 HAS_LXML = False
391
392 from ansible.module_utils.basic import AnsibleModule, json_dict_bytes_to_unicode, missing_required_lib
393 from ansible.module_utils.common.text.converters import to_bytes
394
395 _IDENT = r"[a-zA-Z-][a-zA-Z0-9_\-\.]*"
396 _NSIDENT = f"{_IDENT}|{_IDENT}:{_IDENT}"
397 # Note: we can't reasonably support the 'if you need to put both ' and " in a string, concatenate
398 # strings wrapped by the other delimiter' XPath trick, especially as simple XPath.
399 _XPSTR = "('(?:.*)'|\"(?:.*)\")"
400
401 _RE_SPLITSIMPLELAST = re.compile(f"^(.*)/({_NSIDENT})$")
402 _RE_SPLITSIMPLELASTEQVALUE = re.compile(f"^(.*)/({_NSIDENT}" + ")/text\\(\\)=" + _XPSTR + "$")
403 _RE_SPLITSIMPLEATTRLAST = re.compile(f"^(.*)/(@(?:{_NSIDENT}))$")
404 _RE_SPLITSIMPLEATTRLASTEQVALUE = re.compile(f"^(.*)/(@(?:{_NSIDENT}))={_XPSTR}$")
405 _RE_SPLITSUBLAST = re.compile(f"^(.*)/({_NSIDENT}" + ")\\[(.*)\\]$")
406 _RE_SPLITONLYEQVALUE = re.compile("^(.*)/text\\(\\)=" + _XPSTR + "$")
407
408
409 def has_changed(doc):
410 orig_obj = etree.tostring(objectify.fromstring(etree.tostring(orig_doc)))
411 obj = etree.tostring(objectify.fromstring(etree.tostring(doc)))
412 return orig_obj != obj
413
414
415 def do_print_match(module, tree, xpath, namespaces):
416 match = tree.xpath(xpath, namespaces=namespaces)
417 match_xpaths = []
418 for m in match:
419 match_xpaths.append(tree.getpath(m))
420 match_str = json.dumps(match_xpaths)
421 msg = f"selector '{xpath}' match: {match_str}"
422 finish(module, tree, xpath, namespaces, changed=False, msg=msg, matches=match_xpaths)
423
424
425 def count_nodes(module, tree, xpath, namespaces):
426 """Return the count of nodes matching the xpath"""
427 hits = tree.xpath(f"count(/{xpath})", namespaces=namespaces)
428 msg = f"found {hits} nodes"
429 finish(module, tree, xpath, namespaces, changed=False, msg=msg, hitcount=int(hits))
430
431
432 def is_node(tree, xpath, namespaces):
433 """Test if a given xpath matches anything and if that match is a node.
434
435 For now we just assume you're only searching for one specific thing."""
436 if xpath_matches(tree, xpath, namespaces):
437 # OK, it found something
438 match = tree.xpath(xpath, namespaces=namespaces)
439 if isinstance(match[0], etree._Element):
440 return True
441
442 return False
443
444
445 def is_attribute(tree, xpath, namespaces):
446 """Test if a given xpath matches and that match is an attribute
447
448 An xpath attribute search will only match one item"""
449
450 # lxml 5.1.1 removed etree._ElementStringResult, so we can no longer simply assume it is there
451 # (https://github.com/lxml/lxml/commit/eba79343d0e7ad1ce40169f60460cdd4caa29eb3)
452 ElementStringResult = getattr(etree, "_ElementStringResult", None)
453
454 if xpath_matches(tree, xpath, namespaces):
455 match = tree.xpath(xpath, namespaces=namespaces)
456 if isinstance(match[0], etree._ElementUnicodeResult):
457 return True
458 elif ElementStringResult is not None and isinstance(match[0], ElementStringResult):
459 return True
460 return False
461
462
463 def xpath_matches(tree, xpath, namespaces):
464 """Test if a node exists"""
465 return bool(tree.xpath(xpath, namespaces=namespaces))
466
467
468 def delete_xpath_target(module, tree, xpath, namespaces):
469 """Delete an attribute or element from a tree"""
470 changed = False
471 try:
472 for result in tree.xpath(xpath, namespaces=namespaces):
473 changed = True
474 # Get the xpath for this result
475 if is_attribute(tree, xpath, namespaces):
476 # Delete an attribute
477 parent = result.getparent()
478 # Pop this attribute match out of the parent
479 # node's 'attrib' dict by using this match's
480 # 'attrname' attribute for the key
481 parent.attrib.pop(result.attrname)
482 elif is_node(tree, xpath, namespaces):
483 # Delete an element
484 result.getparent().remove(result)
485 else:
486 raise Exception("Impossible error")
487 except Exception as e:
488 module.fail_json(msg=f"Couldn't delete xpath target: {xpath} ({e})")
489 else:
490 finish(module, tree, xpath, namespaces, changed=changed)
491
492
493 def replace_children_of(children, match):
494 for element in list(match):
495 match.remove(element)
496 match.extend(children)
497
498
499 def set_target_children_inner(module, tree, xpath, namespaces, children, in_type):
500 matches = tree.xpath(xpath, namespaces=namespaces)
501
502 # Create a list of our new children
503 children = children_to_nodes(module, children, in_type)
504 children_as_string = [etree.tostring(c) for c in children]
505
506 changed = False
507
508 # xpaths always return matches as a list, so....
509 for match in matches:
510 # Check if elements differ
511 if len(list(match)) == len(children):
512 for idx, element in enumerate(list(match)):
513 if etree.tostring(element) != children_as_string[idx]:
514 replace_children_of(children, match)
515 changed = True
516 break
517 else:
518 replace_children_of(children, match)
519 changed = True
520
521 return changed
522
523
524 def set_target_children(module, tree, xpath, namespaces, children, in_type):
525 changed = set_target_children_inner(module, tree, xpath, namespaces, children, in_type)
526 # Write it out
527 finish(module, tree, xpath, namespaces, changed=changed)
528
529
530 def add_target_children(module, tree, xpath, namespaces, children, in_type, insertbefore, insertafter):
531 if is_node(tree, xpath, namespaces):
532 new_kids = children_to_nodes(module, children, in_type)
533 if insertbefore or insertafter:
534 insert_target_children(tree, xpath, namespaces, new_kids, insertbefore, insertafter)
535 else:
536 for node in tree.xpath(xpath, namespaces=namespaces):
537 node.extend(new_kids)
538 finish(module, tree, xpath, namespaces, changed=True)
539 else:
540 finish(module, tree, xpath, namespaces)
541
542
543 def insert_target_children(tree, xpath, namespaces, children, insertbefore, insertafter):
544 """
545 Insert the given children before or after the given xpath. If insertbefore is True, it is inserted before the
546 first xpath hit, with insertafter, it is inserted after the last xpath hit.
547 """
548 insert_target = tree.xpath(xpath, namespaces=namespaces)
549 loc_index = 0 if insertbefore else -1
550 index_in_parent = insert_target[loc_index].getparent().index(insert_target[loc_index])
551 parent = insert_target[0].getparent()
552 if insertafter:
553 index_in_parent += 1
554 for child in children:
555 parent.insert(index_in_parent, child)
556 index_in_parent += 1
557
558
559 def _extract_xpstr(g):
560 return g[1:-1]
561
562
563 def split_xpath_last(xpath):
564 """split an XPath of the form /foo/bar/baz into /foo/bar and baz"""
565 xpath = xpath.strip()
566 m = _RE_SPLITSIMPLELAST.match(xpath)
567 if m:
568 # requesting an element to exist
569 return (m.group(1), [(m.group(2), None)])
570 m = _RE_SPLITSIMPLELASTEQVALUE.match(xpath)
571 if m:
572 # requesting an element to exist with an inner text
573 return (m.group(1), [(m.group(2), _extract_xpstr(m.group(3)))])
574
575 m = _RE_SPLITSIMPLEATTRLAST.match(xpath)
576 if m:
577 # requesting an attribute to exist
578 return (m.group(1), [(m.group(2), None)])
579 m = _RE_SPLITSIMPLEATTRLASTEQVALUE.match(xpath)
580 if m:
581 # requesting an attribute to exist with a value
582 return (m.group(1), [(m.group(2), _extract_xpstr(m.group(3)))])
583
584 m = _RE_SPLITSUBLAST.match(xpath)
585 if m:
586 content = [x.strip() for x in m.group(3).split(" and ")]
587 return (m.group(1), [(f"/{m.group(2)}", content)])
588
589 m = _RE_SPLITONLYEQVALUE.match(xpath)
590 if m:
591 # requesting a change of inner text
592 return (m.group(1), [("", _extract_xpstr(m.group(2)))])
593 return (xpath, [])
594
595
596 def nsnameToClark(name, namespaces):
597 if ":" in name:
598 (nsname, rawname) = name.split(":")
599 return f"{{{namespaces[nsname]}}}{rawname}"
600
601 # no namespace name here
602 return name
603
604
605 def check_or_make_target(module, tree, xpath, namespaces):
606 (inner_xpath, changes) = split_xpath_last(xpath)
607 if (inner_xpath == xpath) or (changes is None):
608 module.fail_json(
609 msg=f"Can't process Xpath {xpath} in order to spawn nodes! tree is {etree.tostring(tree, pretty_print=True)}"
610 )
611 return False
612
613 changed = False
614
615 if not is_node(tree, inner_xpath, namespaces):
616 changed = check_or_make_target(module, tree, inner_xpath, namespaces)
617
618 # we test again after calling check_or_make_target
619 if is_node(tree, inner_xpath, namespaces) and changes:
620 for eoa, eoa_value in changes:
621 if eoa and eoa[0] != "@" and eoa[0] != "/":
622 # implicitly creating an element
623 new_kids = children_to_nodes(module, [nsnameToClark(eoa, namespaces)], "yaml")
624 if eoa_value:
625 for nk in new_kids:
626 nk.text = eoa_value
627
628 for node in tree.xpath(inner_xpath, namespaces=namespaces):
629 node.extend(new_kids)
630 changed = True
631 # module.fail_json(msg="now tree=%s" % etree.tostring(tree, pretty_print=True))
632 elif eoa and eoa[0] == "/":
633 element = eoa[1:]
634 new_kids = children_to_nodes(module, [nsnameToClark(element, namespaces)], "yaml")
635 for node in tree.xpath(inner_xpath, namespaces=namespaces):
636 node.extend(new_kids)
637 for nk in new_kids:
638 for subexpr in eoa_value:
639 # module.fail_json(msg="element=%s subexpr=%s node=%s now tree=%s" %
640 # (element, subexpr, etree.tostring(node, pretty_print=True), etree.tostring(tree, pretty_print=True))
641 check_or_make_target(module, nk, f"./{subexpr}", namespaces)
642 changed = True
643
644 # module.fail_json(msg="now tree=%s" % etree.tostring(tree, pretty_print=True))
645 elif eoa == "":
646 for node in tree.xpath(inner_xpath, namespaces=namespaces):
647 if node.text != eoa_value:
648 node.text = eoa_value
649 changed = True
650
651 elif eoa and eoa[0] == "@":
652 attribute = nsnameToClark(eoa[1:], namespaces)
653
654 for element in tree.xpath(inner_xpath, namespaces=namespaces):
655 changing = attribute not in element.attrib or element.attrib[attribute] != eoa_value
656
657 if changing:
658 changed = changed or changing
659 if eoa_value is None:
660 value = ""
661 else:
662 value = eoa_value
663 element.attrib[attribute] = value
664
665 # module.fail_json(msg="arf %s changing=%s as curval=%s changed tree=%s" %
666 # (xpath, changing, etree.tostring(tree, changing, element[attribute], pretty_print=True)))
667
668 else:
669 module.fail_json(msg=f"unknown tree transformation={etree.tostring(tree, pretty_print=True)}")
670
671 return changed
672
673
674 def ensure_xpath_exists(module, tree, xpath, namespaces):
675 changed = False
676
677 if not is_node(tree, xpath, namespaces):
678 changed = check_or_make_target(module, tree, xpath, namespaces)
679
680 finish(module, tree, xpath, namespaces, changed)
681
682
683 def set_target_inner(module, tree, xpath, namespaces, attribute, value, create_if_missing=True):
684 changed = False
685
686 try:
687 if not is_node(tree, xpath, namespaces):
688 if not create_if_missing:
689 return changed
690 changed = check_or_make_target(module, tree, xpath, namespaces)
691 except Exception as e:
692 missing_namespace = ""
693 # NOTE: This checks only the namespaces defined in root element!
694 # TODO: Implement a more robust check to check for child namespaces' existence
695 if tree.getroot().nsmap and ":" not in xpath:
696 missing_namespace = "XML document has namespace(s) defined, but no namespace prefix(es) used in xpath!\n"
697 module.fail_json(
698 msg=f"{missing_namespace}Xpath {xpath} causes a failure: {e}\n -- tree is {etree.tostring(tree, pretty_print=True)}",
699 exception=traceback.format_exc(),
700 )
701
702 if not is_node(tree, xpath, namespaces):
703 module.fail_json(
704 msg=f"Xpath {xpath} does not reference a node! tree is {etree.tostring(tree, pretty_print=True)}"
705 )
706
707 if not isinstance(value, str):
708 target = f"attribute '{attribute}' at xpath '{xpath}'" if attribute else f"element text at xpath '{xpath}'"
709 module.fail_json(
710 msg=(
711 f"A non-string value {value!r} was parsed for {target}. "
712 "YAML values for booleans, octals, floats may not yield the string you intended. "
713 """Quote the value to be explicit, like `value: "yes"`."""
714 )
715 )
716
717 for element in tree.xpath(xpath, namespaces=namespaces):
718 if not attribute:
719 changed = changed or (element.text != value)
720 if element.text != value:
721 element.text = value
722 else:
723 changed = changed or (element.get(attribute) != value)
724 if ":" in attribute:
725 attr_ns, attr_name = attribute.split(":")
726 # attribute = "{{%s}}%s" % (namespaces[attr_ns], attr_name)
727 attribute = f"{{{namespaces[attr_ns]}}}{attr_name}"
728 if element.get(attribute) != value:
729 element.set(attribute, value)
730
731 return changed
732
733
734 def set_target(module, tree, xpath, namespaces, attribute, value, create_if_missing):
735 changed = set_target_inner(module, tree, xpath, namespaces, attribute, value, create_if_missing)
736 finish(module, tree, xpath, namespaces, changed)
737
738
739 def get_element_text(module, tree, xpath, namespaces):
740 if not is_node(tree, xpath, namespaces):
741 module.fail_json(msg=f"Xpath {xpath} does not reference a node!")
742
743 elements = []
744 for element in tree.xpath(xpath, namespaces=namespaces):
745 elements.append({element.tag: element.text})
746
747 finish(module, tree, xpath, namespaces, changed=False, msg=len(elements), hitcount=len(elements), matches=elements)
748
749
750 def get_element_attr(module, tree, xpath, namespaces):
751 if not is_node(tree, xpath, namespaces):
752 module.fail_json(msg=f"Xpath {xpath} does not reference a node!")
753
754 elements = []
755 for element in tree.xpath(xpath, namespaces=namespaces):
756 child = {}
757 for key in element.keys():
758 value = element.get(key)
759 child.update({key: value})
760 elements.append({element.tag: child})
761
762 finish(module, tree, xpath, namespaces, changed=False, msg=len(elements), hitcount=len(elements), matches=elements)
763
764
765 def child_to_element(module, child, in_type):
766 if in_type == "xml":
767 infile = BytesIO(to_bytes(child, errors="surrogate_or_strict"))
768
769 try:
770 parser = etree.XMLParser()
771 node = etree.parse(infile, parser)
772 return node.getroot()
773 except etree.XMLSyntaxError as e:
774 module.fail_json(msg=f"Error while parsing child element: {e}")
775 elif in_type == "yaml":
776 if isinstance(child, str):
777 return etree.Element(child)
778 elif isinstance(child, MutableMapping):
779 if len(child) > 1:
780 module.fail_json(msg="Can only create children from hashes with one key")
781
782 (key, value) = list(child.items())[0]
783 if isinstance(value, MutableMapping):
784 children = value.pop("_", None)
785 child_value = value.pop("+value", None)
786
787 node = etree.Element(key, value)
788
789 if children is not None:
790 if not isinstance(children, list):
791 module.fail_json(msg=f"Invalid children type: {type(children)}, must be list.")
792
793 subnodes = children_to_nodes(module, children)
794 node.extend(subnodes)
795
796 if child_value is not None:
797 node.text = child_value
798 else:
799 node = etree.Element(key)
800 node.text = value
801 return node
802 else:
803 module.fail_json(msg=f"Invalid child type: {type(child)}. Children must be either strings or hashes.")
804 else:
805 module.fail_json(msg=f"Invalid child input type: {in_type}. Type must be either xml or yaml.")
806
807
808 def children_to_nodes(module=None, children=None, type="yaml"):
809 """turn a str/hash/list of str&hash into a list of elements"""
810 children = [] if children is None else children
811
812 return [child_to_element(module, child, type) for child in children]
813
814
815 def make_pretty(module, tree):
816 xml_string = etree.tostring(
817 tree, xml_declaration=True, encoding="UTF-8", pretty_print=module.params["pretty_print"]
818 )
819
820 result = dict(
821 changed=False,
822 )
823
824 if module.params["path"]:
825 xml_file = module.params["path"]
826 with open(xml_file, "rb") as xml_content:
827 if xml_string != xml_content.read():
828 result["changed"] = True
829 if not module.check_mode:
830 if module.params["backup"]:
831 result["backup_file"] = module.backup_local(module.params["path"])
832 tree.write(
833 xml_file, xml_declaration=True, encoding="UTF-8", pretty_print=module.params["pretty_print"]
834 )
835
836 elif module.params["xmlstring"]:
837 result["xmlstring"] = xml_string
838 # NOTE: Modifying a string is not considered a change !
839 if xml_string != module.params["xmlstring"]:
840 result["changed"] = True
841
842 module.exit_json(**result)
843
844
845 def finish(module, tree, xpath, namespaces, changed=False, msg="", hitcount=0, matches=tuple()):
846 result = dict(
847 actions=dict(xpath=xpath, namespaces=namespaces, state=module.params["state"]),
848 changed=has_changed(tree),
849 )
850
851 if module.params["count"] or hitcount:
852 result["count"] = hitcount
853
854 if module.params["print_match"] or matches:
855 result["matches"] = matches
856
857 if msg:
858 result["msg"] = msg
859
860 if result["changed"]:
861 if module._diff:
862 result["diff"] = dict(
863 before=etree.tostring(orig_doc, xml_declaration=True, encoding="UTF-8", pretty_print=True),
864 after=etree.tostring(tree, xml_declaration=True, encoding="UTF-8", pretty_print=True),
865 )
866
867 if module.params["path"] and not module.check_mode:
868 if module.params["backup"]:
869 result["backup_file"] = module.backup_local(module.params["path"])
870 tree.write(
871 module.params["path"],
872 xml_declaration=True,
873 encoding="UTF-8",
874 pretty_print=module.params["pretty_print"],
875 )
876
877 if module.params["xmlstring"]:
878 result["xmlstring"] = etree.tostring(
879 tree, xml_declaration=True, encoding="UTF-8", pretty_print=module.params["pretty_print"]
880 )
881
882 module.exit_json(**result)
883
884
885 def main():
886 module = AnsibleModule(
887 argument_spec=dict(
888 path=dict(type="path", aliases=["dest", "file"]),
889 xmlstring=dict(type="str"),
890 xpath=dict(type="str"),
891 namespaces=dict(type="dict", default={}),
892 state=dict(type="str", default="present", choices=["absent", "present"], aliases=["ensure"]),
893 value=dict(type="raw"),
894 attribute=dict(type="raw"),
895 add_children=dict(type="list", elements="raw"),
896 set_children=dict(type="list", elements="raw"),
897 count=dict(type="bool", default=False),
898 print_match=dict(type="bool", default=False),
899 pretty_print=dict(type="bool", default=False),
900 content=dict(type="str", choices=["attribute", "text"]),
901 input_type=dict(type="str", default="yaml", choices=["xml", "yaml"]),
902 backup=dict(type="bool", default=False),
903 strip_cdata_tags=dict(type="bool", default=False),
904 huge_tree=dict(type="bool", default=False),
905 insertbefore=dict(type="bool", default=False),
906 insertafter=dict(type="bool", default=False),
907 create_if_missing=dict(type="bool", default=True),
908 ),
909 supports_check_mode=True,
910 required_by=dict(
911 add_children=["xpath"],
912 attribute=["value"],
913 content=["xpath"],
914 set_children=["xpath"],
915 value=["xpath"],
916 ),
917 required_if=[
918 ["count", True, ["xpath"]],
919 ["print_match", True, ["xpath"]],
920 ["insertbefore", True, ["xpath"]],
921 ["insertafter", True, ["xpath"]],
922 ],
923 required_one_of=[
924 ["path", "xmlstring"],
925 ["add_children", "content", "count", "pretty_print", "print_match", "set_children", "value"],
926 ],
927 mutually_exclusive=[
928 ["add_children", "content", "count", "print_match", "set_children", "value"],
929 ["path", "xmlstring"],
930 ["insertbefore", "insertafter"],
931 ],
932 )
933
934 xml_file = module.params["path"]
935 xml_string = module.params["xmlstring"]
936 xpath = module.params["xpath"]
937 namespaces = module.params["namespaces"]
938 state = module.params["state"]
939 value = json_dict_bytes_to_unicode(module.params["value"])
940 attribute = module.params["attribute"]
941 set_children = json_dict_bytes_to_unicode(module.params["set_children"])
942 add_children = json_dict_bytes_to_unicode(module.params["add_children"])
943 pretty_print = module.params["pretty_print"]
944 content = module.params["content"]
945 input_type = module.params["input_type"]
946 print_match = module.params["print_match"]
947 count = module.params["count"]
948 strip_cdata_tags = module.params["strip_cdata_tags"]
949 huge_tree = module.params["huge_tree"]
950 insertbefore = module.params["insertbefore"]
951 insertafter = module.params["insertafter"]
952 create_if_missing = module.params["create_if_missing"]
953
954 # Check if we have lxml 2.3.0 or newer installed
955 if not HAS_LXML:
956 module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_IMP_ERR)
957 elif LooseVersion(LXML_VERSION_STR) < LooseVersion("2.3.0"):
958 module.fail_json(msg="The xml ansible module requires lxml 2.3.0 or newer installed on the managed machine")
959 elif LooseVersion(LXML_VERSION_STR) < LooseVersion("3.0.0"):
960 module.warn("Using lxml version lower than 3.0.0 does not guarantee predictable element attribute order.")
961
962 infile = None
963 try:
964 # Check if the file exists
965 if xml_string:
966 infile = BytesIO(to_bytes(xml_string, errors="surrogate_or_strict"))
967 elif os.path.isfile(xml_file):
968 infile = open(xml_file, "rb")
969 else:
970 module.fail_json(msg=f"The target XML source '{xml_file}' does not exist.")
971
972 # Parse and evaluate xpath expression
973 if xpath is not None:
974 try:
975 etree.XPath(xpath)
976 except etree.XPathSyntaxError as e:
977 module.fail_json(msg=f"Syntax error in xpath expression: {xpath} ({e})")
978 except etree.XPathEvalError as e:
979 module.fail_json(msg=f"Evaluation error in xpath expression: {xpath} ({e})")
980
981 # Try to parse in the target XML file
982 try:
983 parser = etree.XMLParser(remove_blank_text=pretty_print, strip_cdata=strip_cdata_tags, huge_tree=huge_tree)
984 doc = etree.parse(infile, parser)
985 except etree.XMLSyntaxError as e:
986 module.fail_json(msg=f"Error while parsing document: {xml_file or 'xml_string'} ({e})")
987 finally:
988 if infile:
989 infile.close()
990
991 # Ensure we have the original copy to compare
992 global orig_doc
993 orig_doc = copy.deepcopy(doc)
994
995 if print_match:
996 do_print_match(module, doc, xpath, namespaces)
997
998 if count:
999 count_nodes(module, doc, xpath, namespaces)
1000
1001 if content == "attribute":
1002 get_element_attr(module, doc, xpath, namespaces)
1003 elif content == "text":
1004 get_element_text(module, doc, xpath, namespaces)
1005
1006 # File exists:
1007 if state == "absent":
1008 # - absent: delete xpath target
1009 delete_xpath_target(module, doc, xpath, namespaces)
1010
1011 # - present: carry on
1012
1013 # children && value both set?: should have already aborted by now
1014 # add_children && set_children both set?: should have already aborted by now
1015
1016 # set_children set?
1017 if set_children is not None:
1018 set_target_children(module, doc, xpath, namespaces, set_children, input_type)
1019
1020 # add_children set?
1021 if add_children:
1022 add_target_children(module, doc, xpath, namespaces, add_children, input_type, insertbefore, insertafter)
1023
1024 # No?: Carry on
1025
1026 # Is the xpath target an attribute selector?
1027 if value is not None:
1028 set_target(module, doc, xpath, namespaces, attribute, value, create_if_missing)
1029
1030 # If an xpath was provided, we need to do something with the data
1031 if xpath is not None:
1032 ensure_xpath_exists(module, doc, xpath, namespaces)
1033
1034 # Otherwise only reformat the xml data?
1035 if pretty_print:
1036 make_pretty(module, doc)
1037
1038 module.fail_json(msg="Don't know what to do")
1039
1040
1041 if __name__ == "__main__":
1042 main()