On 25.01.2017 23:37, mark.to...@dsv.com wrote:
I have a problem where a line that contains a certain space delimited
string must exist in a file.  The string can be anywhere in the line:
start, middle, or end. If a line that contains that string does not exist, then a line with that string needs to be inserted into the file. I have been trying to use the lineinfile module to solve this, but so far I have
been unsuccessful.  Below is the code I have tried:

- lineinfile:
dest: "/path/to/myfile"
regexp: '^(.*)(\s*this_string_must_exist)(\s+.*)$'
line: '\g<1> this_string_must_exist\g<3>'
backrefs: true
state: present

I have tried many variations of the regular expression and line, but
nothing I have tried totally achieves what I am looking for.  I have
verified that the regular expression can locate a line with the string
regardless of where the string is within the line, and if such a line is located it is not modified. But I have not been successful in getting a
new line inserted if it does not already exist.
Does anyone have any suggestions?

The reason it doesn't work is explained in the documentation.

https://docs.ansible.com/ansible/lineinfile_module.html#options

In the comments about the backrefs:
"... and if the regexp doesn't match anywhere in the file, the file will be left unchanged."

So you'll need to find a way to do it without backrefs: yes if you are going to use lineinfile.

--
Kai Stian Olstad

--
You received this message because you are subscribed to the Google Groups "Ansible 
Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/80f37017915143bd01efdb4ddb950742%40olstad.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to