lineinfile module: replace multiple matching lines?

As it is implemented now, the lineinfile module replaces only the last matching line in the given file. I guess the requirement for the line argument (“Must match the value given to regexp”) is there to guarantee idempotence if there are multiple matching lines in the file.

If I’m not mistaken, this requirement would not be necessary if replacing ALL matching lines in the file, would it?

Are there any other reasons for the limitation to the last match?

I’m asking because I just stumbled upon a use case for both the replacement of all matching lines and the replacement line not matching the original expression - we have a file with the same key=value line occuring multiple times where the key should be renamed…

On a sidenote: would it be difficult to have the replacement line include text “captured” from the original line (via regular expression capturing groups)? (I’m a bit reluctant to start developing Ansible modules myself at this time - but I hope this will change :wink:

Perhaps blasphemy, but I'd do this with a shell module call invoking
sed, with an if statement in there with grep to achieve the
idempotence issues. Easy global replace.

But I'm open to new flags.

Perhaps blasphemy, but I’d do this with a shell module call invoking
sed, with an if statement in there with grep to achieve the
idempotence issues. Easy global replace.

Ok, this is what we’re doing right now (in a shell script)… just wanted to try and replace it with a dedicated module, as the lineinfile module seemed so fitting.

But well, no need to reinvent the wheel in this case I guess :slight_smile:

Another option: use template.
For many things I find template easier to deal with and debug because sometimes regexp can be dangerous and difficult to work with.