Ansible lineInFile多次插入



我已经尝试并四处搜索以解决这个问题,但没有任何适合我的问题。

我使用ansible来检索配置,我想以某种方式操作这个配置。我想做的一件事是在正则表达式匹配的行之前添加一个标记,但要在所有行上添加。

hello
something
something
hello
something
hello

应该是:

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

我尝试过使用带有insertbefore选项的模块lineinfile,但这次只在最后一个匹配中添加了一次标记。我也尝试了with_items循环,但我的选项没有改变,我只想在相同regex的所有匹配项上完成,之前添加了相同的字符串。

有什么想法我可以做到这一点吗?

您可以使用替换模块:

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

结果:

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

如果使用此正则表达式:

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

如果您重播任务,则不会添加新的tag:

如果你对小组有问题:

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

最新更新