Question:
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
1 2 3 |
- 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?
Answer:
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):
1 2 3 4 |
- name: Test for line shell: grep -c "^couchbase.host" /database.properties || true register: test_grep |
And then apply the condition to your lineinfile
task:
1 2 3 4 5 6 |
- name: add couchbase host to properties lineinfile: dest: /database.properties line: couchbase.host=127.0.0.1 when: test_grep.stdout == "0" |
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?