Kevin C
Kevin C

Reputation: 5760

Ansible - multiple items in path, but cannot use loop

I'm not sure how to describe the title or my question properly, feel free to edit.

I'll jump right in. I have this working piece of Ansible code:

- file:
    path: "{{ item.item.value.my_folder }}/{{ item.item.value.filename }}"
    state: absent
  loop: "{{ my_stat.results }}"
  when: item.stat is defined and item.stat.exists and item.stat.islnk

If Ansible is run, the task is executed properly, and the file is removed from the system.

Now, the issue. What I want Ansible to do is loop over multiple items described in "path". This way I won't have to create a seperate task for each filename I want to be deleted. Example:

- file:
    path:
      - "{{ item.item.value.my_folder }}/{{ item.item.value.filename }}"
      - "{{ item.item.value.my_folder }}/{{ item.item.value.other_filename }}"
    state: absent
  loop: "{{ my_stat.results }}"
  when: item.stat is defined and item.stat.exists and item.stat.islnk

But Ansible doesn't proces the items in the list described in 'path', so the filesnames will not be deleted. I see I cannot use 'loop', since it is already in use for another value.

Question: How would I configure Ansible so that I can have multiple items in the path and let Ansible delete the filenames, and keeping the current loop intact.

-- EDIT --

Output of the tasks:

I've removed the pastebin url since I believe it has no added value for the question, and the answer has been given.

Upvotes: 1

Views: 332

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39304

As described in the documentation, path is of type path, so Ansible will only accept a valid path in there, not a list.

What you can do, though, is to slightly modify your loop and make a product between your existing list and a list of the filenames properties you want to remove, then use those as the key to access item.item.value (or item.0.item.value now, since we have the product filter applied).

For example:

- file:
    path: "{{ item.0.item.value.my_folder }}/{{ item.0.item.value[item.1] }}"
    state: absent
  loop: "{{ my_stat.results | product(['filename', 'other_filename']) }}"
  when: 
    - item.0.stat is defined
    - item.0.stat.exists 
    - item.0.stat.islnk

PS: a list in a when is the same as adding and statements in the said when

Upvotes: 2

Related Questions