Ansible: Check if a variable contains a list or dictionary

风格不统一 提交于 2021-02-10 03:46:09

问题


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?


回答1:


Example:

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 )

If you test with string, boolean or numeric, the assertion will be false.

Another good option is:

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


来源:https://stackoverflow.com/questions/60729009/ansible-check-if-a-variable-contains-a-list-or-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!