Ansible: Insert line if not exists


I’m trying insert a line in a property file using ansible.
I want to add some property if it does not exist, but not replace it if such property already exists in the file.

I add to my ansible role

But this replaces the property value back to if it exists already in the file.

What I’m doing wrong?


The lineinfile module ensures the line as defined in line is present in the file and the line is identified by your regexp. So no matter what value your setting already has, it will be overridden by your new line.

If you don’t want to override the line you first need to test the content and then apply that condition to the lineinfile module. There is no module for testing the content of a file so you probably need to run grep with a shell command and check the .stdout for content. Something like this (untested):

And then apply the condition to your lineinfile task:

The regexp then can be removed since you already made sure the line doesn’t exist so it never would match.

But maybe you’re doing things back to front. Where does that line in the file come from? When you manage your system with Ansible there should be no other mechanisms in place which interfere with the same config files. Maybe you can work around this by adding a default value to your role?

Leave a Reply