【发布时间】:2015-08-05 19:41:45
【问题描述】:
我想使用 ansible lineinfile 模块(或类似的模块)在特定正则表达式的 每个 匹配之后插入一行。 (lineinfile 只会在最后一个匹配之后插入)。
这看起来很简单。我发誓我先尝试了我的 google-fu。
【问题讨论】:
标签: ansible
我想使用 ansible lineinfile 模块(或类似的模块)在特定正则表达式的 每个 匹配之后插入一行。 (lineinfile 只会在最后一个匹配之后插入)。
这看起来很简单。我发誓我先尝试了我的 google-fu。
【问题讨论】:
标签: ansible
这是一个解决方案,它使用 Ansible 的 replace 模块和负前瞻正则表达式来确保幂等性。
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"
【讨论】:
lineinfile 可能无法进行负前瞻。perl -i -pe 'BEGIN{undef $/; $c="";} $c=s/(after_this)(?!\ninsert_this)/${1}\ninsert_this/smg; END{ print "CHANGED" if $c}' testfile。您可以将它与command 或shell 模块一起使用,如果它替换了至少1 行,上面将打印“CHANGED”到标准输出,因此您需要执行register: result 和changed_when: "'CHANGED' in result.stdout" 之类的操作。这也有效,但您的解决方案更简单:)