ansible

Ansible lineinfile: which match gets replaced?


I am struggling with Ansible lineinfile module. As per the documentation, it should replace the first match in the input file. But as I try the various options, in my input I always get the last match replaced.

Here is the sample code:


# testing backrefs: option
---
- name: testing backrefs option
  hosts: localhost
  vars:
    text: |
      the first match
      this won't fit
      the second match
      no fit here
      the third match
      no fit again
    file: /tmp/regextext.txt
  tasks:

  - name: create test file for lineinfile
    copy:
      content: '{{ text }}'
      dest: "{{ file }}"
  - name: testing backrefs with lineinfile module
    lineinfile:
      regexp: '^(the \w+ match)$'
      line: 'THIS IS \1'
      path: "{{ file }}"
      backrefs: yes
  - debug:
      msg: "To show result, run     cat {{ file }}  "

As far as I inderstand the module documentation this should replace the first line of the input text as the first match to THIS IS the first match.

But my experience is that in this case the last match gets replaced, as the third match to THIS IS the third match.

The output file appears to be like this:

the first match
this won't fit
the second match
no fit here
THIS IS the third match
no fit again

Is my Ansible a rebel, or is this just user error?


Solution

  • Based on documentation,

    If the regexp does match, the last matching line will be replaced.

    and also

    If the first match is required, use(firstmatch=yes).

    This works as expected:

    - name: testing backrefs with lineinfile module
      lineinfile:
        regexp: '^(the \w+ match)$'
        line: 'THIS IS \1'
        path: "{{ file }}"
        backrefs: yes
        firstmatch: yes