checking list of files to see if one exists

382 views
Skip to first unread message

Kathy L

unread,
Jul 5, 2023, 6:59:16 AM7/5/23
to Ansible Project
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?

dulh...@mailbox.org

unread,
Jul 5, 2023, 7:27:15 AM7/5/23
to ansible...@googlegroups.com
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 }}"
 
 

dulh...@mailbox.org

unread,
Jul 5, 2023, 7:33:32 AM7/5/23
to ansible...@googlegroups.com
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
--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/48167645.833040.1688556419468%40office.mailbox.org.
 
---

gunnar wagner | fichtestr. 1, 19386 lübz | fon: 0176 7808 9090

Kathy L

unread,
Jul 5, 2023, 7:35:41 AM7/5/23
to Ansible Project
Oh boy, do I feel dumb.  I should know that - I was making the problem harder than it has to be.  Thank you!

dulh...@mailbox.org

unread,
Jul 5, 2023, 8:46:31 AM7/5/23
to ansible...@googlegroups.com
 
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.
 
 
--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages