From 0ffadc48c633ce01fd0d17fd02494838163afb21 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Thu, 8 Oct 2020 15:01:46 -0700 Subject: [PATCH] init_commit --- plugins/filter/paths.py | 40 +++++++++++++++++++++++ plugins/module_utils/generate_paths.py | 45 ++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 plugins/filter/paths.py create mode 100644 plugins/module_utils/generate_paths.py diff --git a/plugins/filter/paths.py b/plugins/filter/paths.py new file mode 100644 index 0000000..fea97ff --- /dev/null +++ b/plugins/filter/paths.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +""" +flatten a complex object to dot bracket notation +""" +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +from ansible.errors import AnsibleFilterError +from ansible.module_utils.common._collections_compat import ( + Mapping, + MutableMapping, +) + +from ansible_collections.ansible.utils.plugins.module_utils.generate_paths import ( + generate_paths, +) +from jinja2.filters import environmentfilter + + +def to_paths(obj, prepend=None): + return generate_paths(obj, prepend) + + +@environmentfilter +def get_path(environment, vars, path): + string_to_variable = "{{ %s }}" % path + return environment.from_string(string_to_variable).render(**vars) + + +class FilterModule(object): + """ Network filter """ + + def filters(self): + return {"to_paths": to_paths, "get_path": get_path} diff --git a/plugins/module_utils/generate_paths.py b/plugins/module_utils/generate_paths.py new file mode 100644 index 0000000..1ffc538 --- /dev/null +++ b/plugins/module_utils/generate_paths.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +""" +flatten a complex object to dot bracket notation +""" +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +import re +from ansible.module_utils.common._collections_compat import ( + Mapping, + MutableMapping, +) + + +def generate_paths(nested_json, prepend): + out = {} + + def flatten(data, name=""): + if isinstance(data, (dict, Mapping, MutableMapping)): + for key, val in data.items(): + if name: + if re.match("^[a-zA-Z_][a-zA-Z0-9_]*$", key): + nname = name + ".{key}".format(key=key) + else: + nname = name + "['{key}']".format(key=key) + else: + nname = key + flatten(val, nname) + elif isinstance(data, list): + for idx, val in enumerate(data): + flatten(val, "{name}[{idx}]".format(name=name, idx=idx)) + else: + out[name] = data + + if prepend: + flatten({prepend: nested_json}) + else: + flatten(nested_json) + return out