检查文件/文件夹是否存在,并在ansible中执行操作
我有以下代码:检查文件/文件夹是否存在,并在ansible中执行操作,ansible,Ansible,我有以下代码: - 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_f
- 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
最后显示完全备份(成功)或部分备份(失败)的结果。也许您可以尝试以下方法:循环到统计结果,并为每个项目添加存在条件
- 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 }}
[编辑]将
item.item.name
替换为@anarchist建议的item.stat.path
也许您可以尝试以下方法:循环到统计结果,并为每个项目添加存在条件
- 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 }}
[编辑]将
item.item.name
替换为@anarchist建议的item.stat.path
like我这样写是为了得到结果:
- 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打印它我这样写是为了得到结果:
- 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打印它,因为它会给出以下错误:MSG:任务包含一个带有未定义变量的选项。错误是:“ansible.utils.unsafe_proxy.AnsibleUnsafeText对象”没有属性“name”,因此在-name:Backup files之前,请使用:-name:debug debug:var:check_file打印您的var,然后再次运行,并尝试使用良好的varOk更改“item.item.name”,我正在使用'item.stat.path',代码现在可以运行了。我仍然需要在日志中打印已备份的文件、跳过的文件以及“部分”或“完全”备份的结果要注册来自复制模块的结果并使用调试打印,您将拥有备份的文件,对于跳过的文件,您需要创建任务并打印文件“when:not item.stat.exists”可能。。。试着弄清楚你是否理解我的逻辑。它给出了一个错误:MSG:任务包含一个带有未定义变量的选项。错误是:“ansible.utils.unsafe_proxy.AnsibleUnsafeText对象”没有属性“name”,因此在-name:Backup files之前,请使用:-name:debug debug:var:check_file打印您的var,然后再次运行,并尝试使用良好的varOk更改“item.item.name”,我正在使用'item.stat.path',代码现在可以运行了。我仍然需要在日志中打印已备份的文件、跳过的文件以及“部分”或“完全”备份的结果要注册来自复制模块的结果并使用调试打印,您将拥有备份的文件,对于跳过的文件,您需要创建任务并打印文件“when:not item.stat.exists”可能。。。如果你明白我的逻辑,试着弄清楚