Ansible Handler with When Condition – Ansible, Ansible Playbook

ansibleansible-playbook

So I have this playbook

- hosts: localhost
  gather_facts: no
  vars:
    this_thing_is_true: true
    use_handler: false

  tasks:
    - debug:
        msg: 'Notifying handlers'
      changed_when: this_thing_is_true
      notify:
        - me

  handlers:
    - name: me
      debug:
        msg: 'I have been notified'
      when: use_handler is true

And when I run it, as expected, the handler doesn't run.

# ansible-playbook handler.yml

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

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "Notifying handlers"
}

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

I can activate the handler by changing the use_handler variable in the playbook.

 # ansible-playbook handler.yml  
PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "Notifying handlers"
}

RUNNING HANDLER [me] ***********************************************************
ok: [localhost] => {
    "msg": "I have been notified"
}

However, I thought this would also activate the handler … but it doesn't.

# ansible-playbook -e use_handler=true handler.yml


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

TASK [debug] *******************************************************************
changed: [localhost] => {
    "msg": "Notifying handlers"
}

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

Am I doing something wrong?

Best Answer

Change the condition

      when: use_handler|bool
  • The type of the variable use_handler is a string when declared in the INI format of the option

--extra-vars use_handler=true

You can test it if you want to

  - debug:
      var: use_handler|type_debug
  • You don't have to explicitly test it as is true. A plain boolean variable can be used in a test.