lineinfile should have an option to remove duplicate lines matched by regexp

Hello there!

there was a request to enhance the lineinfile module so that it ensures that only one line matching the regexp is left in the file.

https://github.com/ansible/ansible/issues/30235

This issue was closed with the justification that the module “replace” does the job. However, neither the documentation of the replace module nor the comments closing the issue specify how one can use the module to remove all but one matched lines.

Can anyone explain how I could use the replace module to ensure that a file has only one line that matches the regex and not more?

If it is not possible to do that with the replace module (which is obviously not the same as modifying all the occurences of a match), then I guess that one should re-open the issue so that proper solution is discussed and provided (as issue is locked, it is not possible to further the discussion on the topic at the moment).

Kind regards,

Come

Hi Come,

as far as I understand this issue, the replace module would help you to remove all matches and then you can use the lineinfile module to add one line again.

dadav

Hi dadav,

Hmm… Indeed that could be done and probably also be idempotent provided that the duplicate lines and the one you are adding are different.

Thanks for the answer!

Come