drifter
drifter

Reputation: 437

Ansible Loop over dictionaries and lists

I have a variable file which is in following format:

files:
   name: file1
   size: 50K
   location:
     - /var/tmp
     - /nfsvol
     - /tmp
    users:
     - user1
     - user2
     - user3

I want task file to be generated in a following way using some loop over dictionaries and lists and it can be passed to playbook:

- name: Build File Repo
  file_repo:
     name: file1
     size: 50K
     location:
       - user1
       - user2
       - user3
     users:
       - /var/tmp
       - /nfs_vol
       - /tmp

The var files can contain many blocks of "files "and I want task file to go through the entire var file using a loop specified in a task file so that each block can be executed on the specified hosts.

Var files can be like this:

files:
   name: file1
   size: 50K
   location:
     - /var/tmp
     - /nfsvol
     - /tmp
    users:
     - user1
     - user2
     - user3

files:
   name: file2
   size: 53K
   location:
     - /var/tmp
     - /nfsvol
   users:
     - user5
     - user21

I tried with sub element and also followed the following thread but it does not meet my purpose; Nested loop with a list and a dictionary

Upvotes: 0

Views: 92

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

It's not possible to

To go through the entire var file using a loop specified in a task

where

var files can contain many blocks of "files"

It's not possible to have "many" variables named "files". Put all "blocks" to a list and loop: "{{ files }}"

files:
  - name: file1
    size: 50K
    location:
      - /var/tmp
      - /nfsvol
      - /tmp
    users:
      - user1
      - user2
      - user3
  - name: file2
    size: 53K
    location:
      - /var/tmp
      - /nfsvol
    users:
      - user5
      - user21

The task below is probably what you want.

tasks:
  - name: Touch files
    file:
      path: "{{ item.1 }}/{{ item.0.name }}"
      state: touch
    loop: "{{ lookup('subelements', files, 'location') }}"

Upvotes: 1

Related Questions