Ansible: find module to create glob of remote files

Unfortunately, with_fileglob  only works on files local to the Ansible orchestrator host.   It will not build a list of files from the remote directory, even if you use something like the copy module that has ‘remote_source: true’.

In these situation, you can use the find module to generate a list of files on the remote host.  For example, this would capture images found in the remote host /tmp directory.

- name: get images in remote /tmp
  find:
    paths: "/tmp"
    file_type: file
    patterns: '*.png,*.jpg,*.jpeg'
  register: image_list

# show data structure result
- debug: msg="{{image_list}}"

This returns a dictionary where the files list can be found in “.files”.  And then within that, the “.path” provides a full path to the remote file.  Here is an example of using that list to copy all images to a web directory.

- name: copy each image to the Apache2 html directory
  copy:
    remote_source: yes
    src: "{{item.path}}"
    dest: "/var/www/html"
  loop: "{{ image_list.files }}"

The “basename” jinja2 filter can be used to parse out just the file name part of the full path if necessary.

{{ item.path | basename }}

 

REFERENCES

ansible, find module

ansible, with_fileglob module

github issue, with_fileglob acts locally