Retrieving file names/sizes in dir

I wish to be able to get the name and filesize of all files under /var/spool/mail. I was trying to do this with the following:

`

  • name: Stat mail dir
    stat:
    path: “{{ item }}”
    with_fileglob:
  • “/var/spool/mail/*”
    register: mail_dir

`

I do not understand how to reference the resulting variable’s output. How would I go about iterating through the various sub items and sizes?

Looking for output such as:

root: 4096
gomer: 124587
pyle: 0

I have been reviewing the docs (perhaps the wrong ones), and I don’t quite understand.

I know I can do this easily with shell, but I am trying to understand how to retrieve information from variables created with a loop.

Probably there are better ways, but I can do it like so:

  • command: “ls {{directory}}”
    register: dir_out

  • debug: var={{item}}
    with_items: dir_out.stdout_lines

  • stat:
    path: “{{ directory }}/{{ item }}”
    with_items: “{{ dir_out.stdout_lines }}”
    register: st

  • name: porint
    debug: “msg={{ st }}”

  • set_fact:
    mystat: “{{ st.results }}”

  • name: pp
    debug: “msg={{ item.stat.path }},{{ item.stat.size }}”
    with_items: “{{ mystat }}”

you pass the directory like:

ansible-playbook -vv -i hosts pb.yaml -e “directory=/someting/”

I wish to be able to get the name and filesize of all files under
/var/spool/mail. I was trying to do this with the following:
    - name: Stat mail dir
      stat:
        path: "{{ item }}"
      with_fileglob:
        - "/var/spool/mail/*"
      register: mail_dir

with_* only work on ansible controller, not on remote host.
So you are probably looking for the find module.

I do not understand how to reference the resulting variable's output. How
would I go about iterating through the various sub items and sizes?

Looking for output such as:

root: 4096
gomer: 124587
pyle: 0

I have been reviewing the docs (perhaps the wrong ones), and I don't quite
understand.

   - find:
       paths: /var/spool/mail
     register: r

   - debug: msg='{{ item.path | basename }}: {{ item.size }}'
     with_items: '{{ r.files }}'

If you like the result in the file you could do this

   - copy:
       content: |
         {% for i in r.files %}
         {{ i.path | basename }}: {{ i.size }}
         {% endfor %}
       dest: /path/to/file

Thanks to both of you. Gave me great ideas. I implemented and tweaked Kai’s suggestion due to simplicity.