Skip to content

Instantly share code, notes, and snippets.

@lestercheung
Last active November 4, 2022 11:20
Show Gist options
  • Save lestercheung/c020b894593ebf52a25b699f6b169418 to your computer and use it in GitHub Desktop.
Save lestercheung/c020b894593ebf52a25b699f6b169418 to your computer and use it in GitHub Desktop.
A Ansible filter plugin that helps you edit xml files
'''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