]> git.apps.os.sepia.ceph.com Git - ceph-ansible.git/commitdiff
DNM: allow expanding Jinja2 template for Ansible custom plugin
authorRishabh Dave <ridave@redhat.com>
Mon, 15 Oct 2018 19:02:42 +0000 (00:32 +0530)
committerSébastien Han <seb@redhat.com>
Wed, 31 Oct 2018 08:38:59 +0000 (09:38 +0100)
This code should probably move to Ansible codebase.

Signed-off-by: Rishabh Dave <ridave@redhat.com>
plugins/actions/validate.py

index e6e40f9fe671433db240d4f8e7dc4e1203004ee4..40cbc6eabda2c5f5034799b538b419d31d896fe7 100644 (file)
@@ -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 = "<class 'ansible.parsing.yaml.objects.AnsibleUnicode'>"
+        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