Search code examples
linuxansibleprovisioningansible-facts

Ansible: from a list of directories, filter out only existing dirs


I'm trying to create an Ansible playbook that will check a list of directories, and filter that list to only include existing directories, and store that list to a variable (fact?). In addition to storing a filtered list of existing directories, I'd also like to store the first found existing directory to a different variable.

I'm having some difficulty getting that to work and feel like I'm making it more difficult that it should be. Any suggestions?

- hosts: all
  vars:
   my_dirs:
   - "/a/"
   - "/b/"
   - "/c/"
  tasks:

  - name: Checking existing file name
    stat:
      path: "{{ item }}"
    with_items: "{{ my_dirs }}"
    register: check_file_name

  - name: Set fact
    set_fact:
       existing_paths: "{{ item.stat.path }}"
    with_items:
      "{{ check_file_name.results }}"
    when: item.stat.exists | default(False) | bool

Solution

  • I think you almost got it working but might require some change in the playbook as below the results collected in an array:

    
      - set_fact: existing_paths="{{ [] }}"
    
      - name: Set fact
        set_fact:
           existing_paths: "{{ existing_paths +[item.stat.path] }}"
        with_items:
          "{{ check_file_name.results }}"
        when: item.stat.exists