On 19. des. 2016 14:47, Łukasz Górski wrote:
I need to create a nested loop referencing a variable from the outer loop.
Basically something along the lines of:

hosts = [{'name': 'first', 'limit': 3}, {'name': 'second', 'limit': 5}]
for host in hosts:
    for i in range(1, host['limit'] + 1):
        print('%s-%d' % (host['name'], i))

For all I see it's not quite possible using with_nested or with_subelements
(how do I refer to the item coming from the first loop?). I cannot
enumerate all the items, they are simple int values, but their numer may be
quite large.

Is there something to the built-in loops I am missing which could possibly
help me using range() with limit coming from a dictionary from the first
loop/data set?

Check out loop_control
https://docs.ansible.com/ansible/playbooks_loops.html#loop-control

hosts.yml
---
- debug: msg="{{ outer_item.name }}-{{ item }}"
  with_sequence: start=1 end={{ outer_item.limit }}

playbook.yml
- hosts: localhost
  vars:
    hosts:
      - name: 'first'
        limit: 3
      - name: 'second'
        limit: 5

  tasks:
    - include: hosts.yml
      with_items: "{{ hosts }}"
      loop_control:
        loop_var: outer_item

--
Kai Stian Olstad

--
You received this message because you are subscribed to the Google Groups "Ansible 
Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/4ef65fab-a801-3c9f-e55e-b69952990a2f%40olstad.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to