Ansible – How to Use Ansible Replace with Regex Across Multiple Lines

ansible

In ansible, I'd like to replace this:

  <sadmin>
    <user>admin@localhost</user>
  </sadmin>

with this:

<sadmin>
   <user>user1@somedomain</user>
   <user>user2@somedomain</user>
   <user>user3@somedomain</user>
 </sadmin>

I've tried using the replace module, but don't know if the regex can span multiple lines (how would I use python raw notation for newlines?). I tried the xml module but I don't think this is actually an XML file since it kept adding a <?xml version='1.0' encoding='UTF-8'?> header to the top of the file. How can I do this? Better to use a template?

  - name: add replacements to jabber config files
    replace:
      path   : "/etc/jabberd2/{{ item.path }}"
      regexp : "{{ item.regex }}"
      replace: "{{ item.replace }}"
    with_items:
      - { path: 'muc.xml', regex: 'conference.localhost', replace: 'conference.mydomain' }
      - { path: 'muc.xml', regex: '<sadmin>.*</sadmin>',      replace: '<sadmin><user>user1@somedomain</user>\n<user>user2@somedomain</user></sadmin>' }

Best Answer

The play below does what is requested

    - replace:
        path: test.xml
        regexp: '<user>admin@localhost<\/user>'
        replace: |-
          <user>user1@somedomain</user>
            <user>user2@somedomain</user>
            <user>user3@somedomain</user>

The next example below shows how to replace the whole sadmin section

    - replace:
        path: test.xml
        regexp: '(<sadmin>[\s\S]*)</sadmin>'
        replace: |-
          <sadmin>
            <user>user1@somedomain</user>
            <user>user2@somedomain</user>
            <user>user3@somedomain</user>
          </sadmin>