如果变量包含布尔值,我如何在Ansible中失败任务?我想为Ansible的手册执行输入验证
这些变量是通过从YAML文件加载它们作为extra_args传递的。 我曾尝试以下,但它不工作:如果变量包含布尔值,我如何在Ansible中失败任务?我想为Ansible的手册执行输入验证
- name: Check if variable are of type boolean
fail:
msg: "Variable '{{ item }}' is not a boolean"
when: item is not bool
with_items: "{{ required_boolean_vars }}"
而且,类似于布尔值,我怎么能这样做的整数,字典和对象类型相同。
有一种普遍的type_debug
filter它返回类型,因此对于布尔条件为:
when: "item | type_debug == 'bool'"`
的另一种方法:
when: item is sameas true or item is sameas false
对于词典:
when: item is mapping
对于清单:
when: item is iterable
此外,上述条件检查item
为是布尔,你在标题问道。添加not
如果你想考对面为您的代码表明...
有趣的是,你可以测试什么时候一个项目不是字符串,但不是当一个项目不bool时... –
我测试了布尔,布尔,布尔......没有一个是有效的。这工作。谢谢@techraf,干得不错。 –
一种解决方法,我发现失败的任务,如果不是boolean类型变量是
- name: Check if variable are of type boolean
assert:
that: "{{ item }} == false or {{ item }} == true"
msg: "Variable {{ item }} is not of type boolean"
with_items: "{{ required_boolean_vars }}"
其中required_boolean_vars包含的变量列表我想检查。
'that:'是一个Jinja2表达式本身,不要在里面使用大括号。 –
什么是“对象”类型? – techraf