Created
October 20, 2020 13:09
-
-
Save ganeshrn/94eefdbaa0508797cc5d9d3bfa584295 to your computer and use it in GitHub Desktop.
validate_filter.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from copy import deepcopy | |
from ansible.errors import AnsibleError | |
from ansible.module_utils._text import to_native | |
from ansible_collections.ansible.utils.plugins.module_utils.validator.base import ( | |
load_validator, | |
) | |
from ansible_collections.ansible.utils.plugins.module_utils.common.utils import ( | |
to_list, | |
) | |
from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import ( | |
check_argspec, | |
) | |
try: | |
import yaml | |
try: | |
from yaml import CSafeLoader as SafeLoader | |
except ImportError: | |
from yaml import SafeLoader | |
HAS_YAML = True | |
except ImportError: | |
HAS_YAML = False | |
ARGSPEC_CONDITIONALS = {} | |
import epdb | |
def validate(*args, **kwargs): | |
epdb.st() | |
if len(args) < 2: | |
raise AnsibleError("Missing either 'data' or 'criteria' value in filter input," | |
"refer ansible.utils.validate filter plugin documentation for detials") | |
spec = { | |
"data": args[0], | |
"criteria": args[1], | |
} | |
if kwargs.get("engine"): | |
spec.update({"engine": kwargs["engine"]}) | |
argspec = deepcopy(DOCUMENTATION) | |
argspec_obj = yaml.load(argspec, SafeLoader) | |
argspec_result = check_argspec(yaml.dump(argspec_obj), "action", schema_conditionals=ARGSPEC_CONDITIONALS, **spec) | |
if argspec_result.get("failed"): | |
raise AnsibleError('%s with errors: %s' % (argspec_result.get("msg"), argspec_result.get("errors"))) | |
validator_engine, validator_result = load_validator(engine=spec["engine"], | |
data=spec["data"], | |
criteria=spec["criteria"], | |
plugin_vars=kwargs, | |
) | |
if validator_result.get("failed"): | |
raise AnsibleError('validate lookup plugin failed with errors: %s' % validator_result.get("msg")) | |
try: | |
result = validator_engine.validate() | |
except Exception as exc: | |
raise AnsibleError( | |
"Unhandled exception from validator '{validator}'. Error: {err}".format( | |
validator=spec["engine"], err=to_native(exc) | |
) | |
) | |
return to_list(result.get("errors", [])) | |
class FilterModule(object): | |
""" index_of """ | |
def filters(self): | |
"""a mapping of filter names to functions""" | |
return {"validate": validate} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment