Ansible: Insert line if not exists

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):

- name: Test for line
  shell: grep -c "^couchbase.host" /database.properties || true
  register: test_grep

And then apply the condition to your lineinfile task:

- 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?


This is possible by simply using lineinfile and check_mode:

- name: Check if couchbase.host is already defined
  lineinfile:
    state: absent
    path: "/database.properties"
    regexp: "^couchbase.host="
  check_mode: true
  changed_when: false # This just makes things look prettier in the logs
  register: check

- name: Define couchbase.host if undefined
  lineinfile:
    state: present
    path: "/database.properties"
    line: "couchbase.host=127.0.0.1"
  when: check.found == 0