Stat.exists with list of variables in ansible
28,740
The problem is that you are registering check_file_id
in a loop. You need to read the documentation on using register
in a loop, which discusses the implications of doing this. Your variable has a results
key that contains the result of each iteration of the loop. You can see that in your debug
output.
In subsequent tasks, you should iterate over check_file_id.results
instead of file_vars
, like this:
- hosts: localhost
gather_facts: false
vars:
file_vars:
- {id: 1, name: foo}
- {id: 2, name: bar}
tasks:
- name: Checking existing file id
stat:
path: ./files/{{ item.id }}.conf
with_items: "{{ file_vars }}"
register: check_file_id
- name: Checking existing file name
stat:
path: ./files/{{ item.name }}.conf
with_items: "{{ file_vars }}"
register: check_file_name
- debug:
msg: 'file id {{item.item.id}} (name {{item.item.name}}) exists'
with_items: "{{ check_file_id.results }}"
when: item.stat.exists
- debug:
msg: 'file name {{item.item.name}} (id {{item.item.id}}) exists'
with_items: "{{ check_file_name.results }}"
when: item.stat.exists
Author by
Admin
Updated on December 21, 2021Comments
-
Admin over 2 years
I have a problem with checking existing files using dictonary in Ansible.
tasks: - name: Checking existing file id stat: path=/tmp/{{ item.id }}.conf with_items: "{{ file_vars }}" register: check_file_id - name: Checking existing file name stat: path=/tmp/{{ item.name }}.conf with_items: "{{ file_vars }}" register: check_file_name - name: Checking file exists debug: msg='File_id exists' when: check_file_id.stat.exists == True - name: Checking file name exists debug: msg='File name exists' when: check_file_name.stat.exists == True vars: file_vars: - { id: 1, name: one } - { id: 2, name: two }
Then, if I trying to run playbook, I got the error:
FAILED! => {"failed": true, "msg": "The conditional check 'check_file_id.stat.exists == True' failed. The error was: error while evaluating conditional (check_file_id.stat.exists == True): 'dict' object has no attribute 'stat'\n\n
I've tried to debug it:
- debug: var=check_file_id
and got:"results": [ { "_ansible_item_result": true, "_ansible_no_log": false, "changed": false, "invocation": { "module_args": { "checksum_algorithm": "sha1", "follow": false, "get_checksum": true, "get_md5": true, "mime": false, "path": "/tmp/1.conf" }, "module_name": "stat" }, "item": { "id": 1, "name": "one" }, "stat": { "exists": false } }, { "_ansible_item_result": true, "_ansible_no_log": false, "changed": false, "invocation": { "module_args": { "checksum_algorithm": "sha1", "follow": false, "get_checksum": true, "get_md5": true, "mime": false, "path": "/tmp/2.conf" }, "module_name": "stat" }, "item": { "id": 2, "name": "two" }, "stat": { "exists": false } } ]
Where I am wrong? Is is possible to use
stat.exists
with list of variables?Thanks for answer!