ansible: using with_items with notify handler


I want to pass a variable to a notification handler, but can’t find anywhere be it here on SO, the docs or the issues in the github repo, how to do it. What I’m doing is deploying multiple webapps, and when the code for one of those webapps is changed, it should restart the service for that webapp.

I got this to work, somewhat:

(Put it in test.yml and run it with ansible-playbook test.yml -c local.)

But this registers the result of the first task and conditionally loops over that in the second task. My problem is that it gets messy when you have two or more tasks that need to notify the second task! For example, restart the web service if either the code was updated or the configuration was changed.

AFAICT, there’s no way to pass a variable to a handler. That would cleanly fix it for me. I found some issues on github where other people run into the same problem, and some syntaxes are proposed, but none of them actually work.

Including a sub-playbook won’t work either, because using with_items together with include was deprecated.

In my playbooks, I have a site.yml that lists the roles of a group, then in the group_vars for that group I define the list of webapps (including the versions) that should be installed. This seems correct to me, because this way I can use the same playbook for staging and production. But maybe the only solution is to define the role multiple times, and duplicate the list of roles for staging and production.

So what is the wisdom here?


I finally solved it by splitting the apps out over multiple instances of the same role. This way, the handler in the role can refer to variables that are defined as role variable.

In site.yml:

In roles/something/tasks/main.yml:

In roles/something/handlers/main.yml:

Seems a lot less hackish than the first solution!

Leave a Reply