tyson.junk
tyson.junk

Reputation: 53

Ansible modify elements of list

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.

Upvotes: 4

Views: 1427

Answers (2)

Russ Starr
Russ Starr

Reputation: 111

Maybe using file_type: directory in the find module will work?

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

Upvotes: 4

MrName
MrName

Reputation: 2529

If I am understanding correctly, you simply want a list of all directories, and not files. If this is the case, it looks like ansible has the file_type parameter, which can be set to directory.

http://docs.ansible.com/ansible/latest/find_module.html

Upvotes: 2

Related Questions