Nested conditional loop

19 views
Skip to first unread message

Miguel David

unread,
Jan 11, 2017, 10:19:16 AM1/11/17
to Ansible Project
Hi all,

I have a dictionary on my site_vars.yml something like this:

services:
  - name: "service1"
    ...
    foo: "bar"

The playbook calls the role:

- name: Configure backend 
  hosts: backend
  gather_facts: true
  become: yes
  roles:
    - { role: myrole, type: 'bar' }

And on the tasks main.yml

- name: do stuff
  file: path=/var/www/html/{{ item.name }} state=directory
  with_items: "{{ services }}"
  when: type == "bar" and item.foo == "bar"

I am aware this is not elegante. What I would like to do is to have a task which will only execute when the type passed from the invocation of the role matches the value of the variable foo. I tried a couple of with_x alternatives, but as I don't know the order with which when and with_items executes, I'm stuck.

Can anyone chip in with a solution to this basic problem?

Thanks,
Miguel

Johannes Kastl

unread,
Jan 20, 2017, 8:53:34 AM1/20/17
to ansible...@googlegroups.com
Hi,

did you already solve your problem?

On 11.01.17 12:08 Miguel David wrote:

> And on the tasks main.yml
>
> - name: do stuff
> file: path=/var/www/html/{{ item.name }} state=directory
> with_items: "{{ services }}"
> when: type == "bar" and item.foo == "bar"

Normally this should be "split" up into as many separate tasks as you
have services in {{ services }}. Each one is run evaluating the
when-conditition. So one of them should work...

https://docs.ansible.com/ansible/playbooks_loops.html
> Also be aware that when combining when with with_items (or any other loop statement), the when statement is processed separately for each item. See The When Statement for an example.

https://docs.ansible.com/ansible/playbooks_conditionals.html#the-when-statement

Try to debug this using the debug task, drop the type in when and see,
what works:

- debug: msg="Works with {{ item.name }}"
when: 'item.foo == "bar"'

Johannes

signature.asc
Reply all
Reply to author
Forward
0 new messages