Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify how to use variables with handlers #54928

Merged
23 changes: 23 additions & 0 deletions docs/docsite/rst/user_guide/playbooks_intro.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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!
acozine marked this conversation as resolved.
Show resolved Hide resolved
- name: restart "{{ web_service_name }}"
acozine marked this conversation as resolved.
Show resolved Hide resolved

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:

samdoran marked this conversation as resolved.
Show resolved Hide resolved
.. code-block:: yaml+jinja

tasks:
- name: Set host variables based on distribution
include_vars: "{{ ansible_facts.distribution }}.yml"
samdoran marked this conversation as resolved.
Show resolved Hide resolved

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:
Expand Down