Ansible delete Files with wildcard/regex/glob with exception

Viewed 2110

I want to delete files based on a wildcard but also add exceptions to the rule.

- hosts: all
  tasks:
  - name: Ansible delete file wildcard
    find:
      paths: /etc/wild_card/example
      patterns: "*.txt"
      use_regex: true
    register: wildcard_files_to_delete

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ wildcard_files_to_delete.files }}"

For example I want to except a file named "important.txt". How can I do that?

1 Answers

Just add a when condition to the task that deletes files. E.g., something like:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path != '/etc/wild_card/example/important.txt'
    with_items: "{{ wildcard_files_to_delete.files }}"

This will skip a specific file. If you have a list of files to skip you could do this instead:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path not in files_to_skip
    with_items: "{{ wildcard_files_to_delete.files }}"
    vars:
      files_to_skip:
        - /etc/wild_card/example/important.txt
        - /etc/wild_card/example/saveme.txt

And if you want to preserve files based on some sort of pattern, you could make use of ansible's match or search tests:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path is not search('important.txt')
    with_items: "{{ wildcard_files_to_delete.files }}"
Related