'Loop through a list of folders to delete old ones

I want to implement some sort of rotation on subdirectories of folders in a list. Say I have dir1 and dir2, I need to go inside each of them and delete all folders older than X days in dir1 and Y days in dir2.

vars:
  backups:
    dir1:
      name: dir1
      days: 10d
    dir2:
      name: dir2
      days: 3d

I've tried to create a task like this

- name: find all folders
  find:
    paths: "/home/user1/{{ item.value.name }}"
    age: "{{ item.value.days }}"
    file_type: directory
  loop: "{{ lookup('dict', backups) }}"
  register: dirsOlderThanXd  

But, dirsOlderThanXd has a strange format. If there were no loop and just a single directory next step would be something like

- name: remove old folders
  file:
    path: "{{ item.path }}" 
    state: absent
  with_items: "{{ dirsOlderThanXd.files }}"

Documentation says

When you use register with a loop, the data structure placed in the variable will contain a results attribute that is a list of all responses from the module. This differs from the data structure returned when using register without a loop.

So, it's expected, but, how exactly do I work with this output? Or am I doing it all completely wrong?



Solution 1:[1]

You can access the list — results — of list — files — using a map filter, then flatten the resulting list of list:

- name: remove old folders
  file:
    path: "{{ item.path }}" 
    state: absent
  loop: "{{ dirsOlderThanXd.results | map(attribute='files') | flatten }}"
  loop_control:
    label: "{{ item.path }}"

Given the two tasks:

- name: find all folders
  find:
    paths: "/home/user1/{{ item.value.name }}"
    age: "{{ item.value.days }}"
    file_type: directory
  loop: "{{ backups | dict2items }}"
  loop_control:
    label: "{{ item.key }}"
  register: dirsOlderThanXd  
  vars:
    backups:
      dir1:
        name: dir1
        days: 10d
      dir2:
        name: dir2
        days: 3d

- name: remove old folders
  file:
    path: "{{ item.path }}" 
    state: absent
  loop: "{{ dirsOlderThanXd.results | map(attribute='files') | flatten }}"
  loop_control:
    label: "{{ item.path }}"

This would yields something along the line of:

TASK [find all folders] **************************************************
ok: [localhost] => (item=dir1)
ok: [localhost] => (item=dir2)

TASK [remove old folders] ************************************************
changed: [localhost] => (item=/home/user1/dir1/foo)
changed: [localhost] => (item=/home/user1/dir1/bar)
changed: [localhost] => (item=/home/user1/dir2/qux)
changed: [localhost] => (item=/home/user1/dir2/baz)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1