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

imj*_*gel 4 ansible

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

- hosts: localhost
  remote_user: root

  roles:
    - role: ansible-aks
      name: myaks
      resource_group: myresourcegroup
Run Code Online (Sandbox Code Playgroud)

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

- name: Assert AKS Variables
  assert:
    that: "{{ item }} is defined"
    msg: "{{ item  }} is not defined"
  with_items:
    - name
    - resource_group
Run Code Online (Sandbox Code Playgroud)

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

imj*_*gel 8

例子:

在字典的情况下,很容易:

---
- 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 )
Run Code Online (Sandbox Code Playgroud)

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

  - name: Assert if list
    assert:
      that: >
           ( mylist is defined ) and ( mylist is not mapping )
           and ( mylist is iterable ) and ( mylist is not string )
Run Code Online (Sandbox Code Playgroud)

如果您使用字符串、布尔值或数字进行测试,则断言将为假。

另一个不错的选择是:

  - 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" )
Run Code Online (Sandbox Code Playgroud)

  • 为什么最后提到`type_debug`解决方案呢?这看起来像是一个更喜欢我的解决方案...... (3认同)
  • @stackprotector我想知道同样的事情,经过一些搜索后,我在[官方文档](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tests.html#type-tests)中发现了这个小片段这建议使用类型测试而不是屈服于使用“type_debug”的诱惑。遗憾的是,它确实没有给出任何理由。 (3认同)