checking list of files to see if one exists

I have a list of 6 files; if any of them exist already, I need to delete it. If none of them exist just keep going. What I have below is giving me errors that ‘tmp_files.stat.exists is false’. Here is what I have:

  • name: Check to see if one file exists already

stat:
path: “/work/{{ item }}”
loop: “{{ possible_file_names }}”
register: tmp_files

  • debug:
    msg: “file exists”
    when: tmp-file.exists

How do I “stop” the loop when a file exists? And if it doesn’t, keep going through the loop?

hi,

you want to delete those files, if they exist, right?

  • name: delete file, if it exists

ansible.builtin.file:
state: absent
path: “/work/{{ item }}”
loop:

  • file1

  • file2

  • file3

  • file4

  • file5

  • file6

  • all loop items will be set into the disired state (absent).

  • If that state is reached (file is ‘absent’) Ansible is happy and won’t do anything.

  • If that state is not reached (file is not ‘absent’) Ansible will make sure the state is there (aka remove the file)

If you want to define those files elsewehere then in the playbook itself you can also create a variable and then just put the variable in the path line (where now {{ item }} is set

path: “/work/{{ file_to remove }}”

the below example requires that your local user (with whom you are running the playbook) has sufficient privilegdes to remove files in your path location.
If not, you’ll have to add

become: true
become_user: user_with_sufficient_privileges

at the same level as loop

Oh boy, do I feel dumb. I should know that - I was making the problem harder than it has to be. Thank you!

normally I am at the ‘do I feel dumb’ side of the conversation.
So it’s really great whether for once I can help someone else out.