danday74
danday74

Reputation: 57251

Can I use the same Ansible handler twice in one playbook execution?

I am trying to create a file to denote that an execution of a script / command has been done

I know we should avoid script / command but here I cannot

So to prevent re-execution I am creating a file to denote it has already been executed

This works for the latter task but not the former!

I'm wondering if the same handler can be used twice or not

tasks ..

- set_fact: donefile=nodesource_setup

- name: Ensure node install script executed
  shell: ~/tmp/nodesource_setup.sh >> ~/tmp/nodesource_setup.log
  args:
    creates: ~/tmp/{{ donefile }}.done # Cannot one line this
  notify: Done

- set_fact: donefile=ensure-npm-does-not-use-unicode

- name: Ensure npm does not use unicode
  command: npm config set unicode false
  args:
    creates: ~/tmp/{{ donefile }}.done
  notify: Done

handlers ..

- name: Done
  copy:
    content: "done"
    dest: ~/tmp/{{ donefile }}.done
    force: no

Upvotes: 1

Views: 1660

Answers (1)

techraf
techraf

Reputation: 68649

A handler is a task that is run once:

  • after all other tasks had been run (default)
  • on meta: flush_handlers task (the "notify" flag is reset and if a handler is notified again it will be run again)

The problem with your code is that at the time of execution of the Done handler, your donefile variable will have the last value of donefile=ensure-npm-does-not-use-unicode.


You can add the task:

- meta: flush_handlers

before you change the value of donefile, so that for a given value the handlers will be run. The only problem is that it doesn't make much sense - it can be a regular task not a handler.

The raison d'etre of a handler is to prevent it from being executed more than once even though several tasks might request it.

If you want to run it once, you can just go with a regular task or a task with when condition.

Upvotes: 3

Related Questions