Search code examples
ansible

Using Block in Handler - Ansible


I am writing a handler for an Ansible role to stop and start docker. The stop is written as follows in handlers/main.yml

- name: stop docker
  block:

    - name: stop docker (Debian based)
      block:

        - name: stop service docker on debian, if running
          systemd: name=docker state=stopped

        - name: stop service docker.socket on debian, if running
          systemd: name=docker.socket state=stopped

      when: ansible_pkg_mgr == "apt"
  
    - name: stop docker (CentOS based)
      block:

        - name: stop service docker on CentOS, if running
          service:
            name: docker
            state: stopped

        - name: stop service docker.socket on CentOS, if running
          service:
            name: docker
            state: stopped

      when: ansible_pkg_mgr == "yum"

Then in my tasks/main file, I'm calling stop docker

---
- name: test
  command: echo "Stopping docker" 

  notify:
    - stop docker

The error I'm receiving is ERROR! Unexpected Exception, this is probably a bug: 'Block' object has no attribute 'notified_hosts'

If I run this as a task in a playbook it works.

Is there a way to use block in an Ansible handler?


Solution

  • According your error message it seems that Ansible do not provide block functionality for handlers.

    Instead you could use an other approach

    handlers:
      - name: Stop Docker
        include_tasks: tasks/stop_docker.yaml
    

    and put the logic into a separate task file.

    Further Information