0

I have a directory of files I'm looping through and I need to get the filename and possibly other information. The win_stat module I think uses PowerShell, so it gets the name, basename, path, I think last modified date, etc. Is there a comparable module for use on Linux? I tried the stat and find modules, but they only get the full path.

I've also tried different filters, like this one from this question:

lookup('file', item.path) | regex_replace('\u0000',' ')).split() | select('match','^[a-z-_/]*[.]y[a]*ml') | list | first | basename

But this throws an error, or returns nothing. I've also tried just passing the path to basename:

item.path | basename

But this also does nothing.

This seems like a super simple thing, so I don't understand why it's so complicated to even need a long filter/replace like that.

I suppose I could just split the path and grab the last element:

item.path | split('/') | last

But this seems messy and I would think Ansible would have a better way to get this information about a file?

So what's the best way to accomplish this?

jerdub1993
  • 355
  • 1
  • 8
  • 2
    There is a lot you are explaining in the question and you even explained your trial, but please remember that a simple example input / desired output is most of the times worth a thousand words. Your whole question could be supersized to _"I have `/path/to/file.ext` and need to extract `file.ext`, how can I do this in Ansible?"_ – β.εηοιτ.βε May 19 '23 at 06:34
  • On the actual question, then. `basename` **is** indeed the filter you want to use. Claiming _"does nothing"_ is of little help, sadly. Could you show us a `debug` return of `item.path` and of `item.path | basename` so we can have a sense of what is really happening? – β.εηοιτ.βε May 19 '23 at 06:45

1 Answers1

2

I think it depends on the way you get the list of your files and the format of this list. You can try this approach :

- find:
    paths: /tmp/test
    patterns: "*.txt"
  connection: local
  register: list_files

- name: Loop files
  debug:
    msg: "Filename {{ item.path | basename }} and size {{ item.size }}"
  loop: "{{ list_files.files }}"

You get the path and use the basename filter.

Just take care the connection: local in find task if you want to search files on remote host you should remove it. If you are looking on the machine which is executing ansible you can keep it

Porzio Jonathan
  • 536
  • 2
  • 13