Inlinefile module keep adding a line when it does exists

Hello
I want to change the configuration of vim, in order to do set mouse=r.

At the beginning this line is commented by default. Using inlinefile module, I check by regexp the line commented and I replace it with the new line like this:

  • name: Uncommenting mouse=a in /etc/vim/vimrc
    lineinfile:
    path: /etc/vim/vimrc
    regexp: ‘^"set mouse=a’
    line: ‘set mouse=r’

First runs is okay, but the second run ansible append another line to the file like this:

TASK [cassandra_preinstall : Uncommenting mouse=a in /etc/vim/vimrc] ***************************************************************************************************************************************
— before: /etc/vim/vimrc (content)
+++ after: /etc/vim/vimrc (content)
@@ -56,3 +56,4 @@
if filereadable(“/etc/vim/vimrc.local”)
source /etc/vim/vimrc.local
endif

+set mouse=r

It is like lineinfile does not care about the regexp result that should be empty.

What I am missing ?

Here is the documentation for lineinmodule regexp section

The regular expression to look for in every line of the file.
For state=present, the pattern to replace if found. Only the last line found will be replaced.
For state=absent, the pattern of the line(s) to remove.
If the regular expression is not matched, the line will be added to the file in keeping withinsertbefore or insertafter settings.
When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement by line to ensure idempotence.
Uses Python regular expressions. See http://docs.python.org/2/library/re.html.

Since you are modifying the line, the regexp should match the initial state, i.e. "set mouse=a and the final state, i.e., set mouse=r
So the task that you should use is as follows

  • name: Uncommenting mouse=a in /etc/vim/vimrc
    lineinfile:
    path: /etc/vim/vimrc
    regexp: ‘^"?set mouse=[ar]’
    line: ‘set mouse=r’

This is my first response in ansible group. Be gentle.

Hello Emmanuel

Thank you very much that works.