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?
CodePudding user response:
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'