Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible: using with_items with notify handler

Tags:

ansible

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.

From this SO question, I got this to work, somewhat:

- hosts: localhost
  tasks:
  - name: "task 1"
    shell: "echo {{ item }}"
    register: "task_1_output"
    with_items: [a,b]
  - name: "task 2"
    debug:
      msg: "{{ item.item }}"
    when: item.changed
    with_items: task_1_output.results

(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?

like image 286
j0057 Avatar asked Sep 05 '14 21:09

j0057


1 Answers

Variables in Ansible are global so there is no reason to pass a variable to handler. If you are trying to make a handler parameterized in a way that you are trying to use a variable in the name of a handler you won't be able to do that in Ansible.

What you can do is create a handler that loops over a list of services easily enough, here is a working example that can be tested locally:

- hosts: localhost
  tasks:
  - file:  >
      path=/tmp/{{ item }}
      state=directory
    register: files_created
    with_items:
      - one
      - two
    notify: some_handler

  handlers:
    - name: "some_handler"
      shell: "echo {{ item }} has changed!"
      when: item.changed
      with_items: files_created.results
like image 98
jarv Avatar answered Sep 19 '22 14:09

jarv