PythonNut
PythonNut

Reputation: 6409

Ansible lineinfile insert after every match

I would like to use the Ansible lineinfile module (or something similar) to insert a line after every match of a particular regular expression (lineinfile will only insert after the last match).

This seems so simple. I swear I tried my Google-fu first.

Upvotes: 1

Views: 4445

Answers (1)

PythonNut
PythonNut

Reputation: 6409

Here's a solution that uses Ansible's replace module with a negative lookahead regex to ensure idempotency.

vars:
  find_this: "Row in the file"
  insert_this: "New line to be inserted"
  filename: "path/to/foo_file.txt"

tasks:
  - name: multiline match and insert
    replace: >
      dest={{ filename }}
      regexp="^({{ find_this }}\n)(?!{{ insert_this }})"
      replace="\1{{ insert_this }}\n"

Upvotes: 6

Related Questions