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
- name: add couchbase host to properties
lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbase.host=127.0.0.1"
But this replaces the property value back to 127.0.0.1 if it exists already in the file.
What I'm doing wrong?
The
lineinfile
module does what it's supposed to: It ensures the line as defined inline
is present in the file and the line is identified by yourregexp
. So no matter what value your setting already has, it will be overridden by your newline
.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 rungrep
with ashell
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?This is the only way I was able to get this to work.
By a long way of "Trials and errors" I come to this:
Ok, here is mine naive solution... probably not a cross-platform and native Ansible (I've just started to use this tool and still learn it), but definitely shorter:
Same idea as presented here : https://stackoverflow.com/a/40890850/7231194
Steps are:
Example