Home > Software engineering >  How to remove elements from a xml file based on the value of a sub element using ansible?
How to remove elements from a xml file based on the value of a sub element using ansible?

Time:06-20

I have multiple item elements like the following one inside a /path/to/content/ element:

<item>
  <label>SOME_TEXT</label>
  <other_elements/>
</item>

Using ansible's community.general.xml module as follows allows me to remove all existing item elements:

- name: "Remove all items"
  become: true
  community.general.xml:
    path: "{{ path_to_my_xml_file }}"
    xpath: /path/to/content/*
    pretty_print: yes
    state: absent

How can I use the community.general.xml module of ansible to only remove an item who's label's value (i.e. SOME_TEXT) matches a string label_of_item_to_remove ?

If it's not possible with community.general.xml what other module could be used to achieve this ?

CodePudding user response:

Q: "Remove an item who's label's value (i.e. SOME_TEXT) matches a string label_of_item_to_remove"

Yes. It is possible. For example, given the file

shell> cat /tmp/test.xml 
<?xml version='1.0' encoding='UTF-8'?>
<doc>
<item>
  <label>SOME_TEXT</label>
  <other_elements/>
</item>
<item>
  <label>OTHER_TEXT</label>
  <other_elements/>
</item>
</doc>

the task below will remove the first item

    - community.general.xml:
        path: /tmp/test.xml
        xpath: "/doc/item[label='{{ label_of_item_to_remove }}']"
        state: absent
      vars:
        label_of_item_to_remove: SOME_TEXT

Running the play with options --check --diff shows

TASK [community.general.xml] *********************************************
--- before
    after
@@ -1,9  1,5 @@
 <?xml version='1.0' encoding='UTF-8'?>
 <doc>
-<item>
-  <label>SOME_TEXT</label>
-  <other_elements/>
-</item>
 <item>
   <label>OTHER_TEXT</label>
   <other_elements/>
  • Related