Search code examples
ansiblejinja2

Ansible - check variable type


Apparently, according to several hours of searching nobody has encountered this use-case:

Its simple - I would like to execute some ansible logic depending on variable type. Basically equivalent of e.g. instanceof(dict, var_name) but in Ansible:

- name: test
  debug:
    msg: "{{ instanceof(var_name, dict) | ternary('is a dictionary', 'is something else') }}"

Is there any way this can be done?


Solution

  • Since Ansible version 2.3 there is type_debug:

    - name: test
      debug:
            msg: "{{ (( var_name | type_debug) == 'dict') | ternary('is a dictionary', 'is something else') }}"
    

    Note that the docs state a preference for 'type tests'.