Ansible lineinfile duplicates line

Question:

I have a simple file at /etc/foo.txt. The file contains the following:

I have the following ansible playbook task to uncomment the line above:

When I first run ansible-playbook, the line gets uncommented and the /etc/foo.txt now contains the following:

However, if I run ansible-playbook again, I get the following:

If I run it yet again, then the /etc/foo.txt file will look like this:

How to avoid this duplications of lines? I just want to uncomment the ‘#bar’ and be done with it.

Answer:

The problem is the task’s regex only matches the commented out line, #bar. To be idempotent, the lineinfile task needs to match both the commented and uncommented state of the line. This way it will uncomment #bar but will pass bar unchanged.

This task should do what you want:

Note the only change was adding a “?” to the regex.

Leave a Reply