问题
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