blockinfile Ansible 模块不会插入给定的正则表达式

blockinfile Ansible module does not insert at the given regex

下面是 test.conf,我希望在行结束标记之前添加一个块,即在以 </VirtualHost>

开头的行之前

猫test.conf

#
##<VirtualHost _default_:443>
<VirtualHost *:443>
#ProxyPreserveHost On
</VirtualHost>

下面是我添加块的剧本:

cat /tmp/test.yml

---
- name: "Play 1"
  hosts: localhost
  tasks:

    - name: Debug
      blockinfile:
        path: "/tmp/test.conf"
        marker: "#"
        state: present
        block: |
            <FilesMatch "^.*\.(css|html?|js|pdf|txt|xml|xsl|gif|ico|jpe?g|png)$">
             Require all granted
            </FilesMatch>
        insertbefore: '^[^#]*</VirtualHost>'

我在在线 python 编辑器 https://regex101.com 上检查了我的 test.conf 和正则表达式 ^[^#]*<\/VirtualHost>,它匹配了正确的行。 在线正则表达式测试器和调试器:PHP、PCRE、Python、Golang 和 JavaScript 在线正则表达式测试器,带有 PHP、PCRE、Python、Golang 和 JavaScript 突出显示的调试器。 regex101.com

文件已更改,但块已插入错误的位置,如下所示:

TASK [Debug] ************************************************************************************************************************************************
changed: [localhost]

PLAY RECAP **************************************************************************************************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

cat /tmp/test.conf

#
<FilesMatch "^.*\.(css|html?|js|pdf|txt|xml|xsl|gif|ico|jpe?g|png)$">
 Require all granted
</FilesMatch>
#
##<VirtualHost _default_:443>
<VirtualHost *:443>
#ProxyPreserveHost On
</VirtualHost>

你能建议我的剧本有什么问题以及如何让它发挥作用吗?

因为ansible specifies in the fine manual that marker: is exactly what it says -- the way it knows where the managed blocks begin and end. Since you chose to use text that is found throughout your file but is unrelated to the managed block sections, ansible just shrugged its shoulders and gave GIGO.

他们甚至有一个关于从 marker::

中遗漏魔术 {mark} 模板参数的专门警告

Using a custom marker without the {mark} variable may result in the block being repeatedly inserted on subsequent playbook runs.

如果您将 marker: 更改为 marker: "#*#*#*" 之类的东西,它就会开始工作……或者至少会工作一次。