Search code examples
ansibleansible-2.x

List directory names using Ansible Find module


I need to find folder names in /home/test directory. Once I have the list of folder names I need to loop over a task. I am able to retrieve the complete path, but not able to retrieve the folder name. is my approach wrong, or is there any easy way to retrieve folder names?

--
- hosts: localhost
  gather_facts: no
  vars:
    Files: []
    namespaces: []
  tasks:
    - name: Recursively find folders under /home/test
      ansible.builtin.find:
         paths: /home/test
         file_type: directory
         recurse: no
      register: output

    - name: Adding Files to the LIST
      set_fact:
        Files: "{{ Files + [item.path]  }}"
      with_items: "{{ output.files }}"

    - name: Remove the path to only and retrieve folder name only
      set_fact:
        namespaces: "{{ namespaces + item | split('/') | last}}"
      with_items: "{{ Files }}"

Error:

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ namespaces + item | split('/') | last}}): can only concatenate list (not \"str\") to list"}


Solution

  • Put the below declaration into the vars

    namespaces: "{{ output.files|map(attribute='path')|map('basename')|list }}"
    

    Example of a complete playbook for testing

    Given the tree

    shell> tree /tmp/test/
    /tmp/test/
    ├── dir_A
    ├── dir_B
    ├── file_1
    └── file_2
    

    the playbook

    - hosts: localhost
    
      vars:
    
        namespaces: "{{ output.files|map(attribute='path')|map('basename')|list }}"
    
      tasks:
    
        - find:
            paths: /tmp/test
            file_type: directory
          register: output
        - debug:
            var: namespaces
    

    gives (abridged)

    namespaces:
      - dir_B
      - dir_A