Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible : how to use the variable ${item} from with_items in notify?

Tags:

ansible

I am new to Ansible and I am trying to create several virtual environments (one for each project, the list of projects being defined in a variable).

The task works well, I got all the folders, however the handler does not work, it does not init each folder with the virtual environment. The ${item} varialbe in the handler does not work. How can I use an handler when I use with_items ?

  tasks:    
    - name: create virtual env for all projects ${projects}
      file: state=directory path=${virtualenvs_dir}/${item}
      with_items: ${projects}
      notify: deploy virtual env

  handlers:
    - name: deploy virtual env
      command: virtualenv ${virtualenvs_dir}/${item}
like image 681
Michael Avatar asked Aug 21 '13 21:08

Michael


People also ask

What is use of With_items in Ansible?

What is Ansible with_items? The Ansible with_items is a handy plugin to perform loop operations in a playbook. The plugin accepts items and then passes them to the calling module. For example, you can pass a list of packages to install and then give each item in the list to the install task.

How do you use nested loops in Ansible?

Ansible's syntax also supports the idea of nested looping. Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task.

What is With_dict in Ansible?

with_dict: - "{{ zones_hash }}" declares a list with a dict as the first index, and Ansible rightfully complains since it expects a dict. The solution kfreezy mentioned works since it actually gives a dictionary to with_dict and not a list: with_dict: "{{ zones_hash }}" Follow this answer to receive notifications.


1 Answers

Handlers are just 'flagged' for execution once whatever (itemized sub-)task requests it (had the changed: yes in its result). At that time handlers are just like a next regular tasks, and don't know about the itemized loop.

A possible solution is not with a handler but with an extratask + conditional

Something like

- hosts: all 
  gather_facts: false
  tasks:
  - action: shell echo {{item}}
    with_items:
    - 1 
    - 2 
    - 3 
    - 4 
    - 5 
    register: task
  - debug: msg="{{item.item}}"
    with_items: task.results
    when: item.changed == True
like image 139
Serge van Ginderachter Avatar answered Sep 16 '22 21:09

Serge van Ginderachter