From 192c0baf03d83741a83918de25fd7ae9a2771cb3 Mon Sep 17 00:00:00 2001 From: Rishabh Dave Date: Tue, 16 Oct 2018 00:32:42 +0530 Subject: [PATCH] DNM: allow expanding Jinja2 template for Ansible custom plugin This code should probably move to Ansible codebase. Signed-off-by: Rishabh Dave --- plugins/actions/validate.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/plugins/actions/validate.py b/plugins/actions/validate.py index e6e40f9fe..40cbc6eab 100644 --- a/plugins/actions/validate.py +++ b/plugins/actions/validate.py @@ -1,6 +1,7 @@ from ansible.plugins.action import ActionBase from distutils.version import LooseVersion +from ansible.errors import AnsibleUndefinedVariable try: from __main__ import display @@ -34,6 +35,15 @@ class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): # we must use vars, since task_vars will have un-processed variables host_vars = task_vars['vars'] + + # process jinja2 templates + reqd_type = "" + for k, v in host_vars.items(): + if str(type(v)) == reqd_type and len(v) > 2: + if v[0] == v[1] == '{' and v[-1] == v[-2] == '}' and v[2] == \ + v[-3] == ' ': + host_vars[k] = self._expand_jinja2_template(v) + host = host_vars['ansible_hostname'] mode = self._task.args.get('mode', 'permissive') @@ -121,6 +131,22 @@ class ActionModule(ActionBase): return result + def _expand_jinja2_template(self, var): + try: + expanded_var = self._templar.template(var, convert_bare=True, fail_on_undefined=True) + if expanded_var == var: + # if expanded_var is not str/unicode type, raise an exception + if not isinstance(expanded_var, string_types): + raise AnsibleUndefinedVariable + # If var name is same as result, try to template it + expanded_var = self._templar.template("{{" + expanded_var + "}}", convert_bare=True, fail_on_undefined=True) + except AnsibleUndefinedVariable as e: + expanded_var = u"VARIABLE IS NOT DEFINED!" + if self._display.verbosity > 0: + expanded_var += u": %s" % str(e) + + return expanded_var + # Schemas -- 2.39.5