2

I am new to ansible. I want to read a var file and then iterate through it. My var file looks like:

Project_name1:
    -a
    -B
    -C
Project_name2:
    -aa
    -bb
Project_name3:
    -ab

Now, my playbook looks like

- name: include the cars and iterate through them
   include_vars:
     file:project.yml
     name:project
   loop:"{{project}}"

I am not sure how can i loop through the var file. I want the Ansible to read first var which is Project_name1 and then read all the list. Then read Project_name2 and read it's list and so on.

hazzy
  • 107
  • 1
  • 8
  • Hi and welcome to SO. You need at least 2 tasks to test that. 1) include the var file (without loop) to have the variable available 2) add a second task with a loop on the included var. Moreover, your var is a dict. [See the doc](https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#iterating-over-a-dictionary) for how to loop on it. – Zeitounator Jan 16 '20 at 07:22

1 Answers1

0

include_vars is right module

e.g.:

var_file.yml

var1: 
 - blabla
 - blabl2

then import it inside your playbook/role

- name: Include variables
  include_vars: 'var_file.yml'

- name: next step is to use variable
  shell: "echo {{ item }}"
  loop: "{{ var1 }}"
max.ivanch
  • 339
  • 2
  • 5
  • Thanks for the answer. I have a question, in the line loop: "{{var}}" What is var? And what do we write in it? – hazzy Jan 16 '20 at 13:15
  • @hazzy sorry. It’s var1. Variable form included file before – max.ivanch Jan 16 '20 at 13:17
  • Thanks a lot. I got the point. But my situation is that i have 3 vars in my var file. For example, var1 has a list, var2 has list var3 has list. How can i iterate through all of them. – hazzy Jan 16 '20 at 14:51
  • Aha. Then it’s more about choosing correct structure. Check with_dict or with_nested. https://docs.ansible.com/ansible/2.4/playbooks_loops.html – max.ivanch Jan 16 '20 at 15:09
  • This is same topic I guess https://stackoverflow.com/questions/42167747/how-to-loop-over-this-dictionary-in-ansible – max.ivanch Jan 20 '20 at 09:17