ansible handlers include_task not work with tags

Viewed 570

I have a problem when trying to invoke an include tasks with tags from handlers but when executing it, it does not take the tags and executes all the tasks of the playbook

services.yaml

- name: stop service
  become: true
  systemd:
    name: httpd
    state: stopped
  tags: stop

- name: start service
  become: true
  systemd:
    name: httpd
    state: started
  tags: start

main.yaml

- hosts: webservers
  tasks:
    - name: ask stop / start
      pause:
        prompt: "please type start or stop"
        echo: yes
      register: ask
      changed_when: true
      notify: service
      tags: restarting
   
  handlers:
    - name: service
      include_tasks: services.yaml
      tags: "{{ ask.user_input }}"

execute

ansible-playbook main.yam -t restarting

When I run it launches all the tasks omitting the tag

1 Answers

There is no point to use tags on handlers. A handler is either notified or not. Use conditions if you want to run handlers conditionally, e.g.

shell> cat services.yaml
- debug:
    msg: stop service
  when: ask.user_input == 'stop'

- debug:
    msg: start service
  when: ask.user_input == 'start'

Then the playbook

shell> cat pb.yml
- hosts: localhost
  tasks:
    - name: ask stop / start
      pause:
        prompt: "please type start or stop"
        echo: true
      register: ask
      changed_when: true
      notify: service
      tags: [restarting, never]
  handlers:
    - name: service
      include_tasks: services.yaml

gives

shell> ansible-playbook pb.yml -t restarting

PLAY [localhost] ***********************************************************

TASK [ask stop / start] ****************************************************
[ask stop / start]
please type start or stop:
changed: [localhost]

RUNNING HANDLER [service] **************************************************
included: /export/examples/example-269/services.yaml for localhost

RUNNING HANDLER [debug] ****************************************************
skipping: [localhost]

RUNNING HANDLER [debug] ****************************************************
ok: [localhost] => 
  msg: start service

PLAY RECAP *****************************************************************
localhost: ok=3 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

Add never tag to ask for the input only when restarting is selected.

Related