Lineinfile - replacing regex instead of placing text after insertafter

Hi guys,

I have some problems with the lineinfile module. I try to add ‘inserted_text’ after ‘#insertbelow’ when ‘this’ has been found in /etc/ansible/lineinfile/lol. This is my task:

That is not how lineinfile work.
It searches for a string, and replace it or add the line.

To do this you would need to combine find module to search for "this" and then run lineinfile on the file.

Hi Kai,

Thank you for your reply. But what is the difference then between regexp and insertafter etc? Is regexp always being replaced? Or what is exactly the logic?

regexp: and insertafter: is separate features in lineinfile.

When lineinfile find the regexp in regexp: it replaces this line with the string in line:
If it can't find the regexp in regexp: the sting in line: is append to end of file(EOF).

When lineinfile find the regexp in insertafter: it add the string in line: after this line, if it's not already exist.
If it can't find the regexp in insertafter: the string in line: is append to end of file(EOF).

These two feature is not meant to be combine in one task, but used in separate tasks.

Very clear, thank you!

Hi Kai,

When looking in ansible-doc lineinfile, it does combine both regexp and insertafter in one task:

  • lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen ’
    insertafter: '^#Listen ’
    line: 'Listen 8080

Is this an error in the docs or are we (I?) missing something?

If you remove the regexp line it will work exactly the same.