Ansible modify elements of list

Viewed 1145

I have a list of files. I want iterate over the list of files extracting just the path to a new list variable.

This gives me my list of files:

- name: sweep directory /foo/bar recursivly 
find:
  paths: /foo/bar
  recurse: yes
  patterns: "*"
  hidden: True
register: sweep_result

- name: build file list
set_fact: 
 all_list: "{{ sweep_result.files | map(attribute='path') | list }}"

- debug: var=all_list

Output:

TASK [debug] *************************************************
ok: [host] => {
    "all_list": [
        "/foo/bar/.hiddenfile", 
        "/foo/bar/file1", 
        "/foo/bar/folder/file1", 
        "/foo/bar/folder/file2.ext",  
    ]
}

This is an example of what I want:

    "paths": [
        "/foo/bar/", 
        "/foo/bar/folder/",   
    ]

I can see that iterating over the all_list like this does work on each element striping off the file and extension leaving me with just a path. I dont know how to do something similar building a new list variable in the process.

- debug: var=item[:item.rfind('/')]
    with_items:
     - "{{ all_list }}"

Iterating over the list may give me duplicate paths. Using the 'unique' filter can solve that. I am sure there is a proper jinja style filter to get me the result I am after. Thanks for any help.

2 Answers
Related