Ansible:检查变量是否包含列表或字典 [英] Ansible: Check if a variable contains a list or dictionary
本文介绍了Ansible:检查变量是否包含列表或字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时,角色需要不同的强制变量,在调用它们时需要定义这些变量.例如
Sometimes, roles need different mandatory variables that needs to be defined when calling them. For instance
- hosts: localhost
remote_user: root
roles:
- role: ansible-aks
name: myaks
resource_group: myresourcegroup
在角色内部,可以这样控制它:
Inside the role, it can be controlled like this:
- name: Assert AKS Variables
assert:
that: "{{ item }} is defined"
msg: "{{ item }} is not defined"
with_items:
- name
- resource_group
我想将列表或字典传递给我的角色,而不是字符串.如何断言变量包含字典或列表?
I want to pass a list or dictionary to my role instead of a string. How can I assert that a variable contains a dictionary or a list?
推荐答案
示例:
对于字典来说,这很容易:
In the case of a dictionary, it is easy:
---
- name: Assert if variable is list or dict
hosts: localhost
connection: local
gather_facts: false
vars:
mydict: {}
mylist: []
tasks:
- name: Assert if dictionary
assert:
that: ( mydict is defined ) and ( mydict is mapping )
但是在检查列表时,我们需要确保它不是映射,不是字符串,并且是可迭代的:
But when checking a list, we need to be sure that is not mapping, not a string and iterable:
- name: Assert if list
assert:
that: >
( mylist is defined ) and ( mylist is not mapping )
and ( mylist is iterable ) and ( mylist is not string )
如果您使用字符串,布尔值或数字进行测试,则断言将为false.
If you test with string, boolean or numeric, the assertion will be false.
另一个好的选择是:
- name: Assert if dictionary
assert:
that: ( mydict is defined ) and ( mydict | type_debug == "dict" )
- name: Assert if list
assert:
that: ( mylist is defined ) and ( mylist | type_debug == "list" )
这篇关于Ansible:检查变量是否包含列表或字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文