ansible

Ansible replace block of text in a specific file


I would like to force replace block of text from "global" to "/global" in a specific file.

For example: From:

SOME DATA...
SOME DATA...
SOME DATA...
<global>
 <white_list>127.0.0.1</white_list>
 <white_list>::1</white_list>
 <white_list>^localhost.localdomain$</white_list>
</global>
SOME DATA...
SOME DATA...
SOME DATA...

To:

SOME DATA...
SOME DATA...
SOME DATA...
<global>
 <white_list>127.0.0.1</white_list>
 <white_list>::1</white_list>
 <white_list>^localhost.localdomain$</white_list>
 <white_list>{{ white_root_vpn }}</white_list>
 <white_list>{{ white_static1 }}</white_list>
</global>
SOME DATA...
SOME DATA...
SOME DATA...

Have you got any idea how to do this?


Solution

  • Have a look at the blockinfile module.

    This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.

    You would use it like:

    - ansible.builtin.blockinfile:
        path: /path/to/file
        marker: "{mark}"
        marker_begin: "<global>"
        marker_end: "</global>"
        block: |-
          <white_list>127.0.0.1</white_list>
          <white_list>::1</white_list>
          <white_list>^localhost.localdomain$</white_list>
          <white_list>{{ white_root_vpn }}</white_list>
          <white_list>{{ white_static1 }}</white_list>
        state: present