Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Block in Handler - Ansible

Tags:

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?


2 Answers

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

  • Ansible Issue #14270
  • Ansible Issue #20493
  • Ansible Issue #42353
  • What's the difference between include_tasks and import_tasks?
like image 186
U880D Avatar answered Mar 10 '26 10:03

U880D


For me, neither block and import_tasks did work (see https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html).

- name: do something else in somewhere else:
  include_tasks: roles/jh_load_services/tasks/main.yml

If that can help

like image 27
jehon Avatar answered Mar 10 '26 08:03

jehon