Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible xml manipulation similar to lineinfile

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?

like image 760
Mike D Avatar asked Jun 21 '15 03:06

Mike D


People also ask

Does Ansible support XML?

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.

Can Ansible edit files?

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.

Which module can be used to change the content of file at runtime in Ansible?

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.


1 Answers

I was just looking into this myself and discovered an ansible-xml module that looks like a great option.

like image 168
Yeroc Avatar answered Sep 16 '22 19:09

Yeroc