lineinfile insertbefore only works once using the same line

I feel like I’m missing something obvious here:

  • name: PostgreSQL install prep 1
    lineinfile: dest=/etc/yum.repos.d/CentOS-Base.repo insertbefore=‘{{item}}’ line=‘exclude=postgresql*’ state=present
    with_items:
  • ‘^#additional packages that may be useful’
  • ‘^#released updates’

This only executes a change for the first item. After much tinkering, I’ve found that the same line cannot be inserted twice even thought the “insertbefore” parameter is different in each instance. I just get an OK for the second item without a change being made.

I’ve found that I can replace the two items with the line if I include a regex set equal to the items, but I don’t want to do this. I want to insert the same line (exclude=postgresql*) before each item.

What am I doing wrong?

I feel like I’m missing something obvious here:

Example of lineinfile with different insertbefore

What am I doing wrong?

Nothing… But Ansible is doing what you tell it, probably not what you want… The documentation is pretty clear, but perhaps not emphatic enough.

If you look at the expansion of what you are running you are basically running this…

  • lineinfile: dest=/etc/yum.repos.d/CentOS-Base.repo insertbefore=‘^#additional packages that may be useful’ line=‘exclude=postgresql*’ state=present

  • lineinfile: dest=/etc/yum.repos.d/CentOS-Base.repo insertbefore=‘^#released updates’ line=‘exclude=postgresql*’ state=present

So the first item looks at the file, finds that exclude=postgresql* doesn’t exist and so adds it before #additional packages that may be useful. Then it gets to the next line and it finds the line in the file so it doesn’t change it.

To get two entries in the file you will have to edit your task. You may be able to change your insertbefore to regexp and then change your line to something like line=‘exclude=postgresql*\n{{ item }}’ I haven’t tried this but it MIGHT work.

I hope that this helps,

Adam