lineinfile behavior replace line if found, add line if not found?

148 views
Skip to first unread message

Bob Tanner

unread,
Apr 17, 2016, 2:31:09 PM4/17/16
to Ansible Project
Struggling with lineinfile behavior. 

The general question: can lineinfile be used to replace a line in a file if it's found and if it's not found add the line to the file?

I've seen posts saying yes, same saying no, same saying don't use lineinfile, use a template.

Here's the recipe I've been trying:

  lineinfile: >
      dest="/tmp/testfile"
      regexp="(.*){{ item.param }}(.*)?$"
      line='{{ item.param }} {{ item.value }}'
      backrefs="yes"
      state="present"
  with_items:
      - { param: 'testparam', value: 'testvalue' }

The contents of /tmp/testfile

blah blahvalue
foo foovalue
ugh ughvalue

I run the task and "testparam testvalue" does not get added to /tmp/testfile

blah blahvalue
foo foovalue
ugh ughvalue
testvalue wrongvalue

Run the task again and I get what I think is the right output

blah blahvalue
foo foovalue
ugh ughvalue
testvalue testvalue

Paul Tötterman

unread,
Apr 18, 2016, 3:31:21 AM4/18/16
to Ansible Project
Hi Bob,
 
The general question: can lineinfile be used to replace a line in a file if it's found and if it's not found add the line to the file?

I've used it successfully like this, but I didn't template my regexp.

Cheers,
Paul 

Paulo "JCranky" Siqueira

unread,
Apr 18, 2016, 8:29:01 AM4/18/16
to Ansible Project

Using "insertafter=EOF" should do the trick.

[]s,


--
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-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/7c3c9db8-c3cd-4d19-8e0e-7280303e93b6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages