Get list of file names from directory

Viewed 387

Im trying to get a list of files from a directory on the machine running ansible, but without the full file path up to the file name.
So far, I have

managed_files: "{{ lookup('fileglob', '../rules/*', wantlist=True) }}

which will return a list of files in the rules directory, but with the full path to the file, eg. /path/to/rules/rule1.yml, when I only want rule1.yml.

I would like to do something like:

managed_files: "{{ lookup('fileglob', '../rules/*', wantlist=True) | basename | list }}"

but this gives an error that basename expects a path-like string, and not a list.
What is the correct way of doing this?

1 Answers

Use map to apply the basename filter on all the elements of the list:

managed_files: >-
  {{ 
    lookup('fileglob', '../rules/*', wantlist=True) 
    | map('basename') 
    | list 
  }}

Given the task:

- debug:
    msg: >- 
      {{ 
        lookup('fileglob', '../rules/*', wantlist=True) 
        | map('basename') 
        | list 
      }}

This yields:

TASK [debug] *************************************************************
ok: [localhost] => 
  msg:
  - rule3.yml
  - rule1.yml
  - rule2.yml
Related