前言

Handlers 是一種特殊類型的 task,只有在被通知(notify)時才會執行。通常用於需要在多個 task 之後執行的操作,比如重新啟動服務、重新載入設定文件等,可以避免不必要的重複動作。

使用方式

  • 定義 handlers:在 playbook 或 role 中定義 handlers。與普通的 tasks 一樣,只是 handlers 會被特殊處理。
  • 通知 handlers:在需要觸發 handlers 的 task 中使用 notify 關鍵字來通知相應的 handler。
  • 執行 handlers:當所有 tasks 執行完畢後,Ansible 會執行被通知的 handlers。
---
- name: Install and configure web server
  hosts: webservers
  become: yes
 
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present
 
    - name: Copy the Apache config file
      template:
        src: templates/apache2.conf.j2
        dest: /etc/apache2/apache2.conf
      notify: 
        - Apache Config Changed
 
  handlers:
    - name: Apache Config Changed
      service:
        name: apache2
        state: restarted

其他用法

Handlers 也可以通知其他 handlers,這在需要進行更複雜的操作時非常有用。 例如:

handlers:
  - name: Restart Apache
    service:
      name: apache2
      state: restarted
    notify: 
      - Reload Firewall
 
  - name: Reload Firewall
    command: firewall-cmd --reload