如果标志为 true 并且文件中有更改,则重新启动 apache

Restart apache if flag is true and there is change in a file

因此,如果 restart_httpd 标志为真并且复制了新证书,我想重新启动 Apache。

如果标志设置为 true 并且文件已更改,我不知道如何让 Ansible 重新启动 Apache。这是我到目前为止想到的,但没有用

  - name: Copy cert
    copy:
      src: "files/{{ cert_name }}"
      dest: "{{ cert_path }}/{{ item }}/"
      owner: root
      group: root
      mode: 0644
      backup: yes
    loop: "{{ list_cert_names }}"
    register: cert_copied

  - name: Restart Apache if variable is true
    debug:
      msg: 'Restart Apache Flag: {{ restart_httpd }}'
    when: restart_httpd and cert_copied.changed
    notify: Restart httpd

在处理程序中测试标志restart_httpd

  handlers:
    - name: Restart httpd
      debug:
        msg: Restart httpd
      when: restart_httpd|bool

鉴于下面的证书,我们假设其中 none 个已经安装

shell> tree files
files
├── cert1.pem
├── cert2.pem
└── cert3.pem

该任务将复制证书并注册更改

    - copy:
        src: "files/{{ item }}"
        dest: "{{ cert_path }}/{{ item }}"
      loop: "{{ list_cert_names }}"
      register: cert_copied
      notify: Restart httpd

    - debug:
        var: cert_copied.results|map(attribute='changed')|list
    - debug:
        var: cert_copied.changed

给予

cert_copied.results|map(attribute='changed')|list:
  - true
  - true
  - true
cert_copied.changed: true

由于任务已更改,处理程序将收到通知。如果标志为真,处理程序将执行任务

RUNNING HANDLER [Restart httpd] ****************************************
ok: [localhost] => 
  msg: Restart httpd

无需明确测试更改。例如,如果没有复制文件,任务不会改变

TASK [copy] ************************************************************
ok: [localhost] => (item=cert1.pem)
ok: [localhost] => (item=cert2.pem)
ok: [localhost] => (item=cert3.pem)


TASK [debug] ***********************************************************
ok: [localhost] => 
  cert_copied.results|map(attribute='changed')|list:
  - false
  - false
  - false

TASK [debug] ***********************************************************
ok: [localhost] => 
  cert_copied.changed: false

您可以看到没有任何变化,因此没有通知处理程序。例如,如果只有一个文件被更改,处理程序将收到通知

TASK [copy] ************************************************************
ok: [localhost] => (item=cert1.pem)
changed: [localhost] => (item=cert2.pem)
ok: [localhost] => (item=cert3.pem)

TASK [debug] ***********************************************************
ok: [localhost] => 
  cert_copied.results|map(attribute='changed')|list:
  - false
  - true
  - false

TASK [debug] ***********************************************************
ok: [localhost] => 
  cert_copied.changed: true

RUNNING HANDLER [Restart httpd] ****************************************
ok: [localhost] => 
  msg: Restart httpd