Last active
November 4, 2022 11:20
-
-
Save lestercheung/c020b894593ebf52a25b699f6b169418 to your computer and use it in GitHub Desktop.
A Ansible filter plugin that helps you edit xml files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''Ansible filters: useful to edit xml configs | |
''' | |
import xml.etree.ElementTree as ET | |
def xml_edit(xml, xpath, attrs={}, txt=None): | |
'''changes is a list of xpath, attributes and text''' | |
root = ET.fromstring(xml) | |
elm = root.find(xpath) | |
if elm is None: | |
tag = xpath[2:] if xpath.startswith('./') else xpath | |
elm = ET.SubElement(root, tag) | |
for k, v in attrs.items(): | |
elm.attrib[k] = v | |
if txt: | |
elm.text = txt | |
return ET.tostring(root).decode('utf-8') | |
class FilterModule(object): | |
def filters(self): | |
return { | |
'xml_edit': xml_edit, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment