from this question on Stack Overflow
Set up a managed_files
variable as an array
- hosts: whatever
vars:
managed_files:
- file1
- file2
- file3
In a playbook, use it like this:
- shell: ls -1 /some/dir
register: contents
- file: path=/some/dir/{{ item }} state=absent
with_items: contents.stdout_lines
when: item not in managed_files
Thanks