Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active January 23, 2020 06:56
Show Gist options
  • Save halberom/34e4c3217e13ea2ec6261013c02bc5d1 to your computer and use it in GitHub Desktop.
Save halberom/34e4c3217e13ea2ec6261013c02bc5d1 to your computer and use it in GitHub Desktop.
ansible - custom filters to test type
[defaults]
filter_plugins = plugins/filter
test_plugins = plugins/test
PLAY [localhost] *********************************************************************************************************************
TASK [assert] ************************************************************************************************************************
ok: [localhost] => {
"changed": false,
"failed": false,
"msg": "All assertions passed"
}
PLAY RECAP ***************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
---
- hosts: localhost
gather_facts: False
connection: local
vars:
mylist:
- one
- abc
- foo
myfloat: 1.245
myint: 10
mystring: foobar
mydict:
key: value
tasks:
- assert:
that:
- mystring|is_string == True
- mystring|get_type == 'string'
- myint|is_int == True
- myint|get_type == 'int'
- myfloat|is_float == True
- myfloat|get_type == 'float'
- mydict|is_dict == True
- mydict|get_type == 'dict'
# plugins/test/type.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from functools import partial
def get_type(value):
result = type(value).__name__
if result == 'AnsibleUnicode':
result = 'string'
return result
def is_type(value, check_type=None):
result = False
if get_type(value) == check_type:
result = True
return result
class TestModule(object):
'''Ansible Arista custom jinja2 filters'''
def tests(self):
return {
'get_type': get_type,
'is_dict': partial(is_type, check_type='dict'),
'is_float': partial(is_type, check_type='float'),
'is_int': partial(is_type, check_type='int'),
'is_list': partial(is_type, check_type='list'),
# a 'string' test is included in core jinja, but Ansible uses AnsibleUnicode
# so handle that.
'is_string': partial(is_type, check_type='string'),
}
@Greffort
Copy link

Excellent, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment