# Ansible check for a file using stat in loop

**URL:** <https://forum.ansible.com/t/ansible-check-for-a-file-using-stat-in-loop/31876>\
**Category:** Ansible Project\
**Created:** [December 27, 2019, 5:22pm UTC](https://forum.ansible.com/t/ansible-check-for-a-file-using-stat-in-loop/31876 "2019-12-27T17:22:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Prudhvi1](https://avatars.discourse-cdn.com/v4/letter/p/d2c977/32.png) [@Prudhvi1](https://forum.ansible.com/u/Prudhvi1)\
**Post date:** [December 27, 2019, 5:22pm UTC](https://forum.ansible.com/t/ansible-check-for-a-file-using-stat-in-loop/31876/1 "2019-12-27T17:22:37Z")

</div>

I’m using stat module in loop to search for a file when defined.

- name: Check for .pub file  
stat:  
path: “{{ playbook\_dir }}/…/vars/{{ item.name }}.pub”  
loop: “{{ UserAddList.add\_users }}”  
register: file\_details  
when: item.authorized\_keys is defined and item.authorized\_keys != “”  
no\_log: true

- name: Fail if .pub key doesn’t exist  
fail:  
msg: ‘{{ item.item.name }} does not have to public key {{ item.item.name }}.pub in the path {{ item.item.authorized\_keys }} file’  
when: item.stat.exists == false or item.stat.exists is not defined  
loop\_control:  
label: “{{ item.stat }}”  
with\_items: “{{ file\_details.results }}”

Input file:

add\_users:

- name: test1\_123  
group: test123  
password: test1\_newcdsaf  
authorized\_keys: “{{ playbook\_dir }}/…/vars/test1\_123.pub”
- name: test1\_1234  
group: test234  
password: test1\_newcdsaf  
authorized\_keys: “”

My input file will have an user entry with optional authorized keys field

Conditions to fail.

The playbook has to fail when authorized\_keys is defined and the .pub key is present on in the location. I’m using stat module to search for the file.

The playbook should not fail when authorized\_keys field is empty as it is valid case.

right now my playbook is failing when authorized\_keys is empty. This is happening because of the loop.

for the item where the authorized\_keys is not defined, I’m seeing the below output.

“skip\_reason”: “Conditional result was False”,  
“skipped”: true

When authorized\_keys is defined.I’m seeing the stat variable in output

“stat”:  
“exists”: false

Please provide any suggestions to fix this.  
Thank you
