Clarify how to use variables with handlers (#54928)

* Add clarification on handler names

Add example on how to use variables in handlers

* Update docs/docsite/rst/user_guide/playbooks_intro.rst
This commit is contained in:
Sam Doran 2019-04-11 11:23:08 -04:00 committed by Alicia Cozine
parent 51c0fda63f
commit f7ed194bc9

View file

@ -405,6 +405,29 @@ Here's an example handlers section::
name: apache
state: restarted
You may want your Ansible handlers to use variables. For example, if the name of a service varies slightly by distribution, you want your output to show the exact name of the restarted service for each target machine. Avoid placing variables in the name of the handler. Since handler names are templated early on, Ansible may not have a value available for a handler name like this::
handlers:
# this handler name may cause your play to fail!
- name: restart "{{ web_service_name }}"
If the variable used in the handler name is not available, the entire play fails. Changing that variable mid-play **will not** result in newly created handler.
Instead, place variables in the task parameters of your handler. You can load the values using ``include_vars`` like this:
.. code-block:: yaml+jinja
tasks:
- name: Set host variables based on distribution
include_vars: "{{ ansible_facts.distribution }}.yml"
handlers:
- name: restart web service
service:
name: "{{ web_service_name | default('httpd') }}"
state: restarted
As of Ansible 2.2, handlers can also "listen" to generic topics, and tasks can notify those topics as follows::
handlers: