Low Orbit Flux Logo 2 F

Ansible - Handlers

Using a handler:



  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
    notify:
    - restart apache

  - name: ensure apache is running
    service:
      name: httpd
      state: started

  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted

Notify multiple handlers:



- name: template configuration file
  template:
    src: template.j2
    dest: /etc/foo.conf
  notify:
     - restart memcached
     - restart apache


handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
    - name: restart apache
      service:
        name: apache
        state: restarted

Using a var ( won’t change if the var changes mid play):




handlers:
# this handler name may cause your play to fail!
- name: restart "{{ web_service_name }}"


Handlers listening to a topic ( decouple handlers from names ):



handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
      listen: "restart web services"
    - name: restart apache
      service:
        name: apache
        state: restarted
      listen: "restart web services"

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"

Manually flush handlers early:



tasks:
   - shell: some tasks go here
   - meta: flush_handlers
   - shell: some other tasks

Define when task is marked changed:



tasks:
  - name: Copy httpd configuration
    ansible.builtin.copy:
      src: ./new_httpd.conf
      dest: /etc/httpd/conf/httpd.conf
    # The task is always reported as changed
    changed_when: True
    notify: Restart apache

Specify a role name to avoid name conflicts:



role_name : handler_name