Ansible:检查变量是否包含列表或字典

时间:2020-03-17 19:26:57

标签: ansible

有时,角色需要不同的强制变量,在调用它们时需要定义这些变量。例如

- hosts: localhost
  remote_user: root

  roles:
    - role: ansible-aks
      name: myaks
      resource_group: myresourcegroup

在角色内部,可以这样控制它:

- name: Assert AKS Variables
  assert:
    that: "{{ item }} is defined"
    msg: "{{ item  }} is not defined"
  with_items:
    - name
    - resource_group

我想将列表或字典传递给我的角色,而不是字符串。如何断言变量包含字典或列表?

1 个答案:

答案 0 :(得分:3)

示例:

对于字典来说,这很容易:

---
- 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 )

但是在检查列表时,我们需要确保它不是映射,不是字符串且可迭代:

  - name: Assert if list
    assert:
      that: >
           ( mylist is defined ) and ( mylist is not mapping )
           and ( mylist is iterable ) and ( mylist is not string )

如果使用字符串,布尔值或数字进行测试,则断言将为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" )