【发布时间】:2020-09-22 11:00:52
【问题描述】:
示例剧本 -
---
- hosts: localhost
vars:
lesson:
name: Physics
students:
- Bob
- Joe
tasks:
- name: Display student names
debug:
msg: '{{ item }}'
loop: "{{ lesson.students }}"
when: item | default("")
上面的剧本可以很好地输出学生姓名。
但是,如果输入更改(如下所示)以致没有定义学生姓名,则会发生错误。如果根据下面的输入未定义列表,是否有一种简单的方法可以让剧本跳过此任务?我意识到如果输入指定 students: [] 会起作用,但由于此输入来自简单用户,他们不会知道这一点。非常感谢!
vars:
lesson:
name: Physics
students:
错误:致命:[本地主机]:失败! => msg: '传递给''loop'的无效数据',它需要一个列表,得到这个代替:。提示:如果您只传递了一个列表/字典,请尝试将 wantlist=True 添加到您的查找调用或使用 q/query 而不是查找。
更新 - 我尝试了以下变体,但仍然遇到相同的错误 -
---
- hosts: localhost
vars:
lesson:
name: Physics
students:
tasks:
- name: Display student names variation 1
debug:
msg: '{{ item }}'
loop: "{{ lesson.students }}"
when: lesson.students is iterable
- name: Display student names variation 2
debug:
msg: '{{ item }}'
loop: "{{ lesson.students }}"
when: lesson.students is not none
- name: Display student names variation 3
debug:
msg: '{{ item }}'
loop: "{{ lesson.students }}"
when: ( item | default("") ) or ( item is not none )
【问题讨论】:
-
“loop”指令在“when”条件之前计算。
标签: ansible