Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Check if a variable contains a list or dictionary

Tags:

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?

like image 214
imjoseangel Avatar asked Mar 17 '20 19:03

imjoseangel


1 Answers

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" )
like image 117
imjoseangel Avatar answered Sep 25 '22 02:09

imjoseangel