0

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?

2 Answers 2

0

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.
0

I got my answer from another forum

The problem is that it’s impractical to pass a bool into a run with key=value style extra variables on the command line. To set a bool, you’ll need to use JSON. Behold:

[utoddl@tango ansible]$ ansible localhost -e use_handler=true -m debug -a '{"msg": "{{ use_handler | type_debug }}"}'
localhost | SUCCESS => {
    "msg": "str"
}
[utoddl@tango ansible]$ ansible localhost -e '{"use_handler": true}' -m debug -a '{"msg": "{{ use_handler | type_debug }}"}'
localhost | SUCCESS => {
    "msg": "bool"
}

Another option was to replace the boolean check in my handler with a string check

when: use_handler == 'true'
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .