Loops and includes

37 views
Skip to first unread message

Bence Takács

unread,
Jul 7, 2016, 4:04:03 AM7/7/16
to Ansible Project
What is the difference between the following syntaxes?


=== 1st scenario


outside.yaml:

---
- include: inside.yaml
vars: my_inner_item: "{{ item }}"
with_items: - A - B - C
 

inside.yaml:

---
- debug: msg="{{my_inner_item}} with {{ item }} is defined" with_items: - 1 - 2 - 3


=== 2nd scenario


outside.yaml:

---
- include: inside.yaml
with_items: - A - B - C

inside.yaml:

---
- set_fact
my_inner_item={{item}}

- debug: msg="{{my_inner_item}} with {{ item }} is defined" with_items: - 1 - 2 - 3

=== 3rd Scenario:

outside.yaml:

---
- include: inside.yaml my_inner_item={{item}}
  with_items: 
    - A
    - B
    - C

inside.yaml:

---
- debug: msg="{{my_inner_item}} with {{ item }} is defined"
  with_items:
    - 1
    - 2
    - 3

... I do not list the old "loop_control" scenario...


By the way: there is an existing issue connected to this topic:
https://github.com/ansible/ansible/issues/14146

Bence Takács

unread,
Jul 7, 2016, 7:59:15 AM7/7/16
to Ansible Project
I think I messed up something :-)
This way my examples are more easy to understand:

=== 1st scenario


outside.yaml:

---
- include: inside.yaml
vars: my_outer_item: "{{ item }}"

with_items: - A - B - C
 

inside.yaml:

---
- debug: msg="{{my_outer_item}} with {{ item }} is defined" with_items: - 1 - 2 - 3


=== 2nd scenario


outside.yaml:

---
- include: inside.yaml
with_items: - A - B - C

inside.yaml:

---
- set_fact
my_outer_item={{item}}

- debug: msg="{{my_
outer_item}} with {{ item }} is defined" with_items: - 1 - 2 - 3

=== 3rd Scenario:

outside.yaml:

---
- include: inside.yaml my_outer_item={{item}}
  with_items: 
    - A
    - B
    - C

inside.yaml:

---
- debug: msg="{{my_outer_item}} with {{ item }} is defined"
  with_items:
    - 1
    - 2
    - 3

Sources:
http://docs.ansible.com/ansible/playbooks_loops.html#loops-and-includes-in-2-0
http://stackoverflow.com/questions/30785281/one-loop-over-multiple-ansible-tasks
https://github.com/ansible/ansible/issues/14146

But it would be good to get some clarification about the differences.

Bence Takács

unread,
Jul 8, 2016, 5:01:16 AM7/8/16
to Ansible Project
Which one is the recommended way, and why?
Reply all
Reply to author
Forward
0 new messages