How to do 3 with_items in the same task ?

29 views
Skip to first unread message

Anand Solomon

unread,
Feb 3, 2020, 7:31:22 PM2/3/20
to Ansible Project
Hi,
I am reading 3 different variable from a text file and want to iterate in 3 different with_items.

variablefile.yml

vars1 :
 - first_value1
 - first_value 2

var2:
 - second_value1
 - second_value2

var3:
 - third_value1
 - third_value2 

I want to read the value from the text file and pass that as a variable in loop. 

        var_value1: "{{ item }}"
      with_items: "{{ var_value1}}"

        var_value2: "{{ item }}"
      with_items: "{{ var_value2}}"

        var_value3: "{{ item }}"
      with_items: "{{ var_value3}}"

Not sure how do I do this ?


Vladimir Botka

unread,
Feb 3, 2020, 11:36:40 PM2/3/20
to Anand Solomon, ansible...@googlegroups.com
On Mon, 3 Feb 2020 16:31:21 -0800 (PST)
Anand Solomon <anand.v...@gmail.com> wrote:

> variablefile.yml
>
> var1:
> - first_value1
> - first_value2
> var2:
> - second_value1
> - second_value2
> var3:
> - third_value1
> - third_value2
>
> I want to read the value from the text file and pass that as a variable in
> loop.

The tasks below

- include_vars: variablefile.yml
- debug:
var: item
loop: "{{ var1 + var2 + var3 }}"

give

"item": "first_value1"
"item": "first_value2"
"item": "second_value1"
"item": "second_value2"
"item": "third_value1"
"item": "third_value2"

HTH,

-vlado

Anand Solomon

unread,
Feb 5, 2020, 9:25:18 AM2/5/20
to Ansible Project
Thanks very much.

Basically what I want is , I have a file to store my variable, it has the following contents

value1: Something1
value2: Something2

privs1: privs_value1
privs2: privs_value2

In my playbook, I want to iterate this 

value: "{{value1}}"
privilege: "{{privs1}}"

value: "{{value2}}"
privilege: "{{privs2}}"

Vladimir Botka

unread,
Feb 5, 2020, 11:12:18 AM2/5/20
to Anand Solomon, ansible...@googlegroups.com
On Wed, 5 Feb 2020 06:25:18 -0800 (PST)
Anand Solomon <anand.v...@gmail.com> wrote:

> value1: Something1
> value2: Something2
>
> privs1: privs_value1
> privs2: privs_value2
>
> In my playbook, I want to iterate this
>
> value: "{{value1}}"
> privilege: "{{privs1}}"
>
> value: "{{value2}}"
> privilege: "{{privs2}}"

Create the lists of the variables and use "zip" too loop them. For example

- set_fact:
value_keys: "{{ hostvars[inventory_hostname].keys()|
select('match', '^value(.*)$')|
list|sort }}"
- set_fact:
value_list: "{{ value_keys|
map('extract', hostvars[inventory_hostname])|
list }}"
- set_fact:
privs_keys: "{{ hostvars[inventory_hostname].keys()|
select('match', '^privs(.*)$')|
list|sort }}"
- set_fact:
privs_list: "{{ privs_keys|
map('extract', hostvars[inventory_hostname])|
list }}"
- debug:
msg: "value: {{ item.0 }} privilege: {{ item.1 }}"
loop: "{{ value_list|zip(privs_list)|list }}"

give

"msg": "value: Something1 privilege: privs_value1"
"msg": "value: Something2 privilege: privs_value2"

HTH,

-vlado
Reply all
Reply to author
Forward
0 new messages