Home > Enterprise >  Ansible - Looping on a list of lists one after another
Ansible - Looping on a list of lists one after another

Time:02-15

Even if this question looks rather simple (and I've been searching and testing a lot), I cannot figure out how to loop on two ore more lists in ansible in a single task.

For instance, a very simple example :

My vars.yml :

list1:
  - /tmp/dir1
  - /tmp/dir2
  - /tmp/dir3

list2:
  - /tmp/dir4
  - /tmp/dir5
  - /tmp/dir6

My task:

task:
 - name: Create basic directories if they do not exist
   file:
     path: "{{ DIRECTORY }}"
     state: directory
   loop: 
     - "{{ list1 }}"
     - "{{ list2 }}"
   loop_control:
     loop_var: DIRECTORY

Obviously I could create all of them in a single task in a single list, but I have ALOT to create, hence my question.

Thanks in advance,

CodePudding user response:

For example, given the lists below

    list1:
      - /tmp/dir1
      - /tmp/dir2
      - /tmp/dir3
    list2:
      - /tmp/dir4
      - /tmp/dir5
      - /tmp/dir6
    list3:
      - /tmp/dir1
      - /tmp/dir4
      - /tmp/dir9

Create a list of these lists, then flatten them and select unique items only, e.g.

    list3: "{{ [list1, list2, list3]|flatten|unique }}"

gives probably what you are looking for

  list3:
  - /tmp/dir1
  - /tmp/dir2
  - /tmp/dir3
  - /tmp/dir4
  - /tmp/dir5
  - /tmp/dir6
  - /tmp/dir9

You can use it in the loop, of course

task:
 - name: Create basic directories if they do not exist
   file:
     path: "{{ DIRECTORY }}"
     state: directory
   loop: "{{ [list1, list2, list3]|flatten|unique }}"
   loop_control:
     loop_var: DIRECTORY

The situation is even simpler if the lists are stored in a file, e.g.

shell> cat vars.yml
list1:
  - /tmp/dir1
  - /tmp/dir2
  - /tmp/dir3
list2:
  - /tmp/dir4
  - /tmp/dir5
  - /tmp/dir6
list3:
  - /tmp/dir1
  - /tmp/dir4
  - /tmp/dir9

Include the variables(lists) from the file into a dictionary

    - include_vars:
        file: vars.yml
        name: lists

This will create the dictionary lists

  lists:
    list1:
    - /tmp/dir1
    - /tmp/dir2
    - /tmp/dir3
    list2:
    - /tmp/dir4
    - /tmp/dir5
    - /tmp/dir6
    list3:
    - /tmp/dir1
    - /tmp/dir4
    - /tmp/dir9

Then, flatten the values and select unique items. The expression below creates the same list as before without explicitly knowing the lists, i.e. you can keep the code untouched and change the data in the file vars.yml only

    list3: "{{ lists.values()|flatten|unique }}"
  • Related