Ansible 正则表达式在文件中添加块时出现错误

Ansible 正则表达式在文件中添加块时出现错误

我想在<IfModule mod_ssl.c></IfModule>之间添加一个块/etc/apache2/mods-available/ssl.conf,如下所示。我使用blockinfileinsertbefore

不幸的是,该块总是被添加到</IfModule>文件底部。我猜我的正则表达式是错误的。

- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    marker: ""
    insertbefore: '^<\/IfModule>'
  notify:
    - Restart apache2

我尝试了以下正则表达式,但没有成功:

insertbefore: '/^<\/IfModule>/m'
insertbefore: "<\/IfModule>"
insertbefore: "</IfModule>"
insertbefore: "</IfModule> "
insertbefore: '^<\/IfModule>$'
insertbefore: "&lt;/IfModule&gt;"
insertbefore: '(?m)^<\/IfModule>\\s?$'
insertbefore: '^</IfModule>\s?$'

如果有人能帮助我修复正则表达式,我将不胜感激。谢谢。

答案1

短篇故事
获胜正则表达式是insertbefore: "^</IfModule>\\s?$"

很长的故事
我有另一个想法来完成所有事情: - 首先,在文件底部
删除一个任务 - 第二,在文件底部添加一个块- 第三,在文件底部 添加一个任务</IfModule>

</IfModule>

我写了第一个新任务:

- name: Apache2 > Removes </IfModule>
  become: yes
  lineinfile:
    dest: /etc/apache2/mods-available/ssl.conf
    regexp: "^</IfModule>\\s?$"
    state: absent

然后我意识到我刚刚写了正确的正则表达式......我的错误是逃避/
:-)

正确的任务是自行管理一切:

- name: Apache2 > update SSL conf
  become: yes
  blockinfile:
    path: /etc/apache2/mods-available/ssl.conf
    block: |
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"

      # Requires Apache >= 2.4.11
      SSLSessionTickets Off

      ## HSTS (mod_headers is required) (15768000 seconds = 6 months)
      Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"

      ## Transmit cookies over secure connection only
      Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
    insertbefore: "^</IfModule>\\s?$"
  notify:
    - Restart apache2

Anx 的评论让我放回 blockinfile 标记以保持任务的幂等性。

答案2

我已经为 ansible blockinfile regex 示例完成了这样的操作

- name: 'NTP configuration for REHEL6 or CentOS6 or SUSE'
   blockinfile:
     path: /etc/ntp.conf
     insertafter: '^# Please'
     block: |
      server 10.121.127.12 iburst
      server 10.122.127.13 iburst
   when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or (ansible_facts['distribution'] == "RedHat" and ansible_facts['distribution_major_version'] == "6")

相关内容