Variables Stat.exists与ansible中的变量列表一起存在
我在Ansible中使用口述检查现有文件时遇到问题Variables Stat.exists与ansible中的变量列表一起存在,variables,ansible,jinja2,ansible-playbook,Variables,Ansible,Jinja2,Ansible Playbook,我在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 }}.con
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 }
然后,如果我试图运行playbook,我会得到错误:
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
我已尝试调试它:
-debug:var=check\u file\u id
得到:
我错在哪里?
是否可以将stat.exists
与变量列表一起使用
谢谢你的回答 问题是您正在循环中注册
检查文件\u id
。您需要阅读,其中讨论了这样做的含义。变量有一个results
键,其中包含循环每次迭代的结果。您可以在debug
输出中看到这一点
在后续任务中,您应该迭代检查文件\u id.results
,而不是文件\u vars
,如下所示:
- 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
- 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