我有以下代码:
- name: check if file/folder exists
stat:
path: "{{ item }}"
register: check_file
with_items:
- ['{{ source_folder }}','/etc/file', '/usr/file', '/root/dir', '/etc/test']
- debug:
msg: "{{ check_file }}"
#msg: "{{ check_file.stat.exists }}"
#msg: "{{ check_file.results }}"
- name: Backup files
copy:
src: "{{ item }}"
dest: "{{ backup_folder }}/{{ datetime }}/files"
with_items:
- ['{{ source_folder }}','/etc/file', '/usr/file', '/root/dir', '/etc/test']
ignore_errors: "{{ not failure_is_critical }}
我想做的是检查文件/文件夹,如果不存在,请继续备份并在日志中写入一些信息,例如:
folder1 found - OK
file1 found - OK
folder2 not found -skipping
file2 not found -skipping
最后显示完全备份(成功)或部分备份(失败)的结果
答案 0 :(得分:1)
也许您可以尝试以下方法:循环访问统计结果,并为每个项目添加存在条件
- name: Backup files
copy:
src: "{{ 'item.stat.path }}"
dest: "{{ backup_folder }}/{{ datetime }}/files"
loop: "{{ check_file.results }}"
when: item.stat.exists
ignore_errors: "{{ not failure_is_critical }}
[EDIT]用item.item.name
取代了item.stat.path
,就像@anarchist建议的那样
答案 1 :(得分:0)
我这样写是为了得到结果:
- name: Set check files result
set_fact:
store_check_file: "{{ check_file.results | map(attribute='stat.exists') | list }}"
- name: Set backup result
set_fact:
backup_result: "{{ 'partial' if false in store_check_file else 'full'}}"
然后我可以使用debug打印它