Search code examples
regexansibleansible-2.xregexp-replace

Ansible 2.5.5 - before attribute in 'replace' module not working


I'm trying to replace only the first occurrence after a specific string. However, ansible would always match all occurrences. Here's the file:

Here's my ansible task:

    - name: Update minPoolSize for CWTxDataSource dataSource
      replace:
        dest: "{{ op_db_path }}"
        after: ".*CWTxDataSourceXA"
        regexp: "^.*minPoolSize=.*$"
        replace: '        <connectionManager maxPoolSize="750" minPoolSize="20" />'
        backup: yes
    <dataSource jndiName="CWTxDataSource">
        <connectionManager maxPoolSize="750" minPoolSize="1" />
    </dataSource>

    <dataSource jndiName="UMDataSource">
        <connectionManager maxPoolSize="750" minPoolSize="1" />
    </dataSource>

in the above sample both connectionManager tags would get updated which is not the desired behavior? How can I update my regexp to only update first match?? I tried the before option in replace module as a workaround but that didn't work for me for some reason.


Solution

  • I found the following line in ansible docs:

    # Prior to Ansible 2.7.10, using before and after in combination did the opposite of what was intended.
    

    so in order for me to use after before as a workaround I had to reverse their values:

        - name: Update minPoolSize for CWTxDataSource dataSource
          # after / before values are reversed in ansible < 2.7
          replace:
            path: "{{ op_db_path }}"
            before: 'jndiName="CWTxDataSource"'
            after: "</dataSource>"
            regexp: 'minPoolSize="\d+"'
            replace: 'minPoolSize="{{ CWTxDS_minPoolSize }}"'
    

    notice the after before values don't really make sense but it works!