14

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?

imjoseangel
  • 3,543
  • 3
  • 22
  • 30

1 Answers1

21

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" )
imjoseangel
  • 3,543
  • 3
  • 22
  • 30
  • 2
    Why do you mention the `type_debug` solution in the end? It looks like a solution to prefer to me... – stackprotector Apr 22 '22 at 12:11
  • 3
    @stackprotector I was wondering the same thing, and after doing some searching I discovered this small piece in the [official documentation](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tests.html#type-tests) which suggest using type testing rather than giving into temptation of using `type_debug`. It does sadly however not give any reasoning for why. – Hrafn Dec 12 '22 at 13:00