Inserting multiple lines in a file after specific line

Hey everyone,

so I want to insert multiple lines into a file after a specific line to create a blacklist. I use lineinfile module and it kinda works but it really doesn’t

This is a snippet of the file where I try to insert new lines:

// List of packages to not update
Unattended-Upgrade::Package-Blacklist {
// “vim”;
// “libc6”;
// “libc6-dev”;
// “libc6-i686”;
};

When I run this action, it works as I expect it:

  • lineinfile: dest=/etc/apt/apt.conf.d/50unattended-upgrades regexp=‘postgresql’ insertafter=“Unattended-Upgrade::Package-Blacklist” line=’ postgresql-9.3’

it makes the snippet look like this:

// List of packages to not update
Unattended-Upgrade::Package-Blacklist {
postgresql-9.3

// “vim”;
// “libc6”;
// “libc6-dev”;
// “libc6-i686”;
};

However, when I have two lineinfile actions following each other, like so:

  • lineinfile: dest=/etc/apt/apt.conf.d/50unattended-upgrades regexp=‘postgresql’ insertafter=“Unattended-Upgrade::Package-Blacklist” line=’ postgresql-9.3’

  • lineinfile: dest=/etc/apt/apt.conf.d/50unattended-upgrades regexp=‘postgresql’ insertafter=“Unattended-Upgrade::Package-Blacklist” line=’ postgresql-9.2’

what happens is that the last action overwrites the same line over and over and the snippet thus looks like this:

// List of packages to not update
Unattended-Upgrade::Package-Blacklist {
postgresql-9.2

// “vim”;
// “libc6”;
// “libc6-dev”;
// “libc6-i686”;
};

I would expect to have

// List of packages to not update
Unattended-Upgrade::Package-Blacklist {
postgresql-9.2

postgresql-9.3

// “vim”;
// “libc6”;
// “libc6-dev”;
// “libc6-i686”;
};

I admit that I don’t get the logic behind lineinfile actions at all. It’s beyond me why regexp=‘’ has to always match line=‘’, and if they don’t actions fails.

So, I’d like to add multiple lines like that, any ideas how I can do this with lineinfile? I know I can have templates, but I’d rather just insert lines in this particular case.

Regexp must match the line because regexp is the thing that decides if the line needs to be inserted or not.

Suppose you wanted to do “insert x=2” if there is no line in the file that contains “x=” already, etc

Well, in

  • lineinfile: dest=/etc/apt/apt.conf.d/50unattended-upgrades regexp=‘postgresql’ insertafter=“Unattended-Upgrade::Package-Blacklist” line=’ postgresql-9.3’

I match against regexp=‘postgresql’ and that line does NOT exist nowhere in the file. So, what does that mean in regards to regexp making decisions? That if a pattern doesn’t exist, the line=‘’ can be inserted? And when pattern does exist, then what? Do nothing?

yes

Thanks to asg on ansible@irc.freenode.net we’ve managed to come up with this

  • lineinfile: dest=/etc/apt/apt.conf.d/50unattended-upgrades regexp=‘$item’ insertafter=“Unattended-Upgrade::Package-Blacklist” line=‘$item’
    with_items:
  • ’ postgresql-9.2’
  • ’ postgresql-9.3’

this inserts multiple lines as I expected.