In Ansible, I'm looking for a technique that works similar to lineinfile
or replace
but for XML files when using templates is not an option. Seems like a very common need.
With XML files, though, it is necessary to specify an xpath
to guarantee the element is present/absent from the correct place in the DOM.
The solution needs to ensure there is a mechanism of replacing an existing node that could look quite a bit different than the target node.
Trivial example XML file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<datasources-configuration xmlns:myns="http://org.someorg.ds/config">
<datasources>
<!-- various other xml -->
<datasource>
<name>MyDS</name>
<jdbcUrl>...</jdbcUrl>
</datasource>
</datasources>
<!-- various other xml -->
</datasources-configuration>
I want to be able to ensure a full multiline block of XML gets inserted/replaced into target XML file given a certain xpath expression is matched. For example, to add the following datasource to datasources:
<datasource>
<name>AnotherDS</name>
<jdbcUrl>...</jdbcUrl>
</datasource>
The best that I've seen is this custom module which breaks on it's own examples: https://github.com/cmprescott/ansible-xml
Does such a module exist or solution recommendations?
Ansible XML module, which is a part of the General ansible collection module and it supports the various parameters (described in the syntax section) to read the content of the XML file, add or remove the child elements or values, print the specific child attributes or the nodes, change the attribute values, etc.
Ansible uses Python's Regular Expressions to modify files with modules like lineinfile . Since everyone loves RegEx, but hates writing them, having tools to make it easier always helps.
The lineinfile - module is the best option, if you just want to add, replace or remove one line. The replace - module is best, if you want to add, replace or delete several lines.
I was just looking into this myself and discovered an ansible-xml module that looks like a great option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With