简体   繁体   中英

Ansible lineInFile insertbefore multiple times

I have tried and searched around to solve this without anything suiting my issue.

Im using ansible to retrieve a config and i want to manipulate this config in a certain way. One thing i want to do is to add a tag before a line with a regex match, but on all of them.

hello
something
something
hello
something
hello

should be:

tag:
hello
something
something
tag:
hello
something
tag:
hello

i have tried using the module lineinfile with the insertbefore option, but this one only adds the tag once to the last match. I also tried with_items loop but my options dont change, i just want to have it done on all matches of the same regex with the same string getting added before.

Any ideas how i can achieve this?

you could use replace module:

  - name: replace txt
    hosts: localhost
    tasks:
      - name: Replace before 
        ansible.builtin.replace:
          path: "./file.txt"
          regexp: '^(hello)$'
          replace: 'tag:\n\1'

result:

tag:
hello
something
something
tag:
hello
something
tag:
hello

if you use this regex:

      regexp: '^(?:tag:\n)?(hello)$'
      replace: 'tag:\n\1'

that doesnt add new tag: if you replay the task

if you have problem with group:

          regexp: '^hello$'
          replace: 'tag:\nhello'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM