Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible lineinfile: add line in a certain place if absent from entire file

Tags:

ansible

I'm trying to create a playbook that will add a line to a file in a specific place if that line is completely absent from the file, but if the line exists anywhere, it does not get added at all.

For example, if the line I want to add is "bar", and the line I want to add after is "foo" I may have 3 files:

file1

foo
bar
baz

file2

foo
baz

file3

foo
baz
bar

In file2, "bar" would be added after "foo". But "bar" is already present in file1 and file3, so it should not be added, even though in file3, it is not immediately after "foo".

I've tried this:

- name: Change File
  lineinfile:
    path: /path/to/file
    line: bar
    insertafter: ^foo$

The problem is with this playbook, if I ruin it on file3, I end up with

foo
bar
baz
bar

It just checks the insertafter, and if the line isn't immediately after that line, it adds it there.

How can I get what I want?

like image 220
ewok Avatar asked Nov 20 '25 04:11

ewok


1 Answers

I needed a regexp line:

- name: Change File
  lineinfile:
    path: /path/to/file
    line: bar
    regexp: ^bar$
    insertafter: ^foo$
like image 125
ewok Avatar answered Nov 24 '25 22:11

ewok