Ansible 条件失败时的可重复性
在我的playbook中,第一个任务将找到一些文件,如果找到,将它们注册到变量中,第二个任务将通过shell传递的命令删除这些文件,问题是第二个任务始终出错,即使变量Ansible 条件失败时的可重复性,ansible,Ansible,在我的playbook中,第一个任务将找到一些文件,如果找到,将它们注册到变量中,第二个任务将通过shell传递的命令删除这些文件,问题是第二个任务始终出错,即使变量cleanup设置为false。这是剧本: tasks: - name: Find tables find: paths: "{{ file path }}" age: "1d" recurse: yes file_type: directory
cleanup
设置为false。这是剧本:
tasks:
- name: Find tables
find:
paths: "{{ file path }}"
age: "1d"
recurse: yes
file_type: directory
when: cleanup
register: cleanup_files
- name: cleanup tables
shell: /bin/cleanup {{ item.path | basename }}
with_items: "{{ cleanup_files.files }} "
when: "cleanup or item is defined"
当cleanup设置为false时,将跳过第一个任务,但第二个错误是:“failed”:true,“msg”:“'dict object'没有属性‘files’”}
项将被定义为上面的任务未运行,因此它是否仍应跳过该任务,因为cleanup
设置为false
我注意到,如果我在第二个任务中将
或
更改为和
,它会跳过任务。我不知道为什么。我想你需要改变第二个时间
when: "cleanup and cleanup_files.files is defined"
你也可以考虑制作<代码>清理<代码>标签。< /p> 将剧本更改为该代码(第二任务的更改),代码之后可以看到更改背后的逻辑:
tasks:
- name: Find tables
find:
paths: "/tmp"
age: "1000d"
recurse: yes
file_type: directory
when: cleanup
register: cleanup_files
- debug: var=cleanup_files
- name: cleanup tables
debug: msg="file= {{ item.path | basename }}"
when: "cleanup_files.files is defined"
with_items: "{{ cleanup_files.files }} "
当您使用cleanup=false
执行时,find
任务将其结果注册到cleanup\u文件
,但您会注意到它没有cleanup\u files.files
属性。当您使用cleanup=true
执行时,您将获得cleanup\u files.files
,如果没有找到符合find
标准的文件,则该文件将为空
所以,第二个任务只需要知道是否定义了cleanup\u files.files
。如果定义了,它可以继续运行。如果没有找到符合条件的文件,则with_items
子句将正确处理它(无文件=>无迭代)
我添加了一个debug
任务来检查cleanup\u文件
,您可以在以下情况下运行并查看其结构:
希望对您有所帮助@techraf感谢您的回复,我有点困惑我将在何处使用循环我很好奇为什么您的解决方案有效,而我的解决方案无效:/在我看来这是对的。OP对你的答案发表评论,声称“它不起作用”,但你没有回答任何问题/