Dawid Gosławski
Dawid Gosławski

Reputation: 2088

Disable handlers from running

Is there any way to stop handlers from running ? I was trying to add tag and use "--skip-tags" to it but it does not work.

I could add next role variable reload_service: true and use it but I've already started using tags and they work great to just re-run part of role.

Handlers are usually used to restart services and I want to run this role without starting service without changing role variables just to cover next case.

I'm using ansible 2.1.2.0

Test case:

mkdir -p test/role/handlers test/role/tasks cd test echo -ne '---\n - command: "echo Test"\n notify: restart\n' > role/tasks/main.yml echo -ne '---\n- name: restart\n command: "echo Handler"\n tags: [handlers]\n' > role/handlers/main.yml echo -ne '---\n- hosts: localhost\n gather_facts: false\n roles:\n - role\n' > play.yml ansible-playbook play.yml --skip-tags handlers

Upvotes: 14

Views: 13677

Answers (3)

Arian
Arian

Reputation: 25

Since v2.5.0, Ansible has an ansible_skip_tags special variable that stores the tags passed with --skip-tags. Since when clauses work with handlers, this is how I'm working around the issue:

- name: Restart nfs-server
  ansible.builtin.service:
      name: nfs-server
      state: restarted
  when: "'tag_you_want_to_skip' not in ansible_skip_tags" # This is the important line

Now --skip-tags tag_you_want_to_skip will work as expected and skip the handler

Upvotes: 2

Steve E.
Steve E.

Reputation: 9353

There is currently no variable within Ansible which lets you test which tags have been specified at runtime.

As you have discovered, handlers run regardless of assigned tags. The documentation does not make it clear whether this is a bug or intended behaviour.

Some options are:

  • Add another variable to the task and use this since handlers can still be conditional on the when: clause.

  • Have the handler include another file with the action and a tag assigned. The file will always be included, but the tag will make the action conditional.

  • Have a tagged action in the task which then sets a local variable for the handler. This conversion in task would allow tags still be used at runtime.

Upvotes: 12

Paddy Newman
Paddy Newman

Reputation: 71

Here's an example of how you could use a variable to skip a handler:

$ cat test.yaml
---
- hosts: localhost
  tasks:
  - copy:
      content: "{{ ansible_date_time.epoch }}" # This will always trigger the handler.
      dest: /tmp/debug
    notify:
      - debug

  handlers:
  - name: debug
    debug:
      msg: Hello from the debug handler!
    when:
    - skip_handlers | default("false") == "false"

Normal use would look like this:

$ ansible-playbook test.yaml

And to skip the handlers:

$ ansible-playbook test.yaml -e skip_handlers=true

Upvotes: 7

Related Questions