If I want to delete some ascending files in a folder while leaving others in ansible, what would that look like?

Viewed 22

The example is you have a folder with files numbered files_0.jpg to files_10.jpg in a folder /tmp/folder.

I'm trying to figure out how to delete files_0.jpg to files_4.jpg while leaving files files_5.jpg to files_10.jpg.

For extra points, same scenario, but, I want to delete files_0.jpg to files_4.jpg and files_8.jpg to files_10.jpg leaving files_5.jpg, files_6.jpg and files_7.jpg.

I'm trying to figure out how to do this in Ansible and I am stuck at trying to use a regex.

1 Answers

Use the range() function in order to loop over the file sequence you want to delete.

To delete files_{0..4}.jpg:

- file:
    state: absent
    path: "/tmp/folder/file_{{ item }}.jpg"
  loop: "{{ range(0, 5) }}"

To delete files_{0..4}.jpg and files_{8..10}.jpg:

- file:
    state: absent
    path: "/tmp/folder/file_{{ item }}.jpg"
  loop: "{{ range(0, 5) | list + range(8, 11) | list  }}"

Given the playbook:

- hosts: localhost
  gather_facts: no

  tasks:
    - file:
        state: absent
        path: "/tmp/folder/file_{{ item }}.jpg"
      loop: "{{ range(0, 5) | list + range(8, 11) | list }}"

This would yield:

TASK [file] *******************************************************************
changed: [localhost] => (item=0)
changed: [localhost] => (item=1)
changed: [localhost] => (item=2)
changed: [localhost] => (item=3)
changed: [localhost] => (item=4)
changed: [localhost] => (item=8)
changed: [localhost] => (item=9)
changed: [localhost] => (item=10)
Related