试试过滤器regex_escape,例如
- lineinfile:
path: test.txt
regexp: "^{{ item|regex_escape }}$"
line: "{{ item }}"
loop:
- '^f.*o(.*)$'
给予
shell> cat test.txt
^f.*o(.*)$
下面是 Perl 示例的 Ansible(Python) 等价物
shell> cat test.yml
---
- hosts: localhost
tasks:
- lineinfile:
path: test.txt
regexp: "^{{ item.regexp }}$"
line: "{{ item.line }}"
loop:
- {line: 'Foo (bar)', regexp: "{{ 'Foo ' ~ '(bar)'|regex_escape }}"}
- {line: 'Foo (bar)', regexp: "{{ 'Fo. ' ~ '(bar)'|regex_escape }}"}
- {line: 'Foo (bar)', regexp: "{{ 'Fo. ' ~ '(ba.)'|regex_escape }}"}
在检查和差异模式下对空的 test.txt 文件运行 playbook 给出
shell> ansible-playbook test.yml -CD
PLAY [localhost] ***************************************************
TASK [lineinfile] **************************************************
--- before: test.txt (content)
+++ after: test.txt (content)
@@ -0,0 +1 @@
+Foo (bar)
changed: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Foo \\(bar\\)'})
--- before: test.txt (content)
+++ after: test.txt (content)
@@ -0,0 +1 @@
+Foo (bar)
changed: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Fo. \\(bar\\)'})
--- before: test.txt (content)
+++ after: test.txt (content)
@@ -0,0 +1 @@
+Foo (bar)
changed: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Fo. \\(ba\\.\\)'})
尽管 regexp 不匹配,但列表中的第三项也被报告已更改。引用模块 lineinfile 参数regexp:“如果正则表达式不匹配,该行将被添加到文件中......”
任务是幂等的。如果文件中存在该行
shell> cat test.txt
Foo (bar)
没有变化
TASK [lineinfile] **************************************************
ok: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Foo \\(bar\\)'})
ok: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Fo. \\(bar\\)'})
ok: [localhost] => (item={'line': 'Foo (bar)', 'regexp': 'Fo. \\(ba\\.\\)'})