From 5b7e8a7bd65f1308e58c3f39627e78db56a3ca39 Mon Sep 17 00:00:00 2001 From: Brian Coca Date: Fri, 7 Apr 2017 11:46:28 -0400 Subject: [PATCH] centralize ansible_managed and other template vars now template lookup supports these again. --- lib/ansible/plugins/action/template.py | 39 ++++---------------------- lib/ansible/plugins/lookup/template.py | 10 +++++-- lib/ansible/template/__init__.py | 36 ++++++++++++++++++++++-- 3 files changed, 47 insertions(+), 38 deletions(-) diff --git a/lib/ansible/plugins/action/template.py b/lib/ansible/plugins/action/template.py index 393e7d318bb..6cad672f9ef 100644 --- a/lib/ansible/plugins/action/template.py +++ b/lib/ansible/plugins/action/template.py @@ -17,17 +17,14 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type -import datetime import os -import pwd -import time from ansible import constants as C from ansible.errors import AnsibleError -from ansible.module_utils.six import string_types from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.plugins.action import ActionBase from ansible.utils.hashing import checksum_s +from ansible.template import generate_ansible_template_vars boolean = C.mk_boolean @@ -110,36 +107,8 @@ class ActionModule(ActionBase): with open(b_source, 'r') as f: template_data = to_text(f.read()) - try: - template_uid = pwd.getpwuid(os.stat(b_source).st_uid).pw_name - except: - template_uid = os.stat(b_source).st_uid - - temp_vars = task_vars.copy() - temp_vars['template_host'] = os.uname()[1] - temp_vars['template_path'] = source - temp_vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(b_source)) - temp_vars['template_uid'] = template_uid - temp_vars['template_fullpath'] = os.path.abspath(source) - temp_vars['template_run_date'] = datetime.datetime.now() - - managed_default = C.DEFAULT_MANAGED_STR - managed_str = managed_default.format( - host = temp_vars['template_host'], - uid = temp_vars['template_uid'], - file = to_bytes(temp_vars['template_path']) - ) - temp_vars['ansible_managed'] = time.strftime( - managed_str, - time.localtime(os.path.getmtime(b_source)) - ) - - searchpath = [] # set jinja2 internal search path for includes - if 'ansible_search_path' in task_vars: - searchpath = task_vars['ansible_search_path'] - # our search paths aren't actually the proper ones for jinja includes. - + searchpath = task_vars.get('ansible_search_path', []) searchpath.extend([self._loader._basedir, os.path.dirname(source)]) # We want to search into the 'templates' subdir of each search path in @@ -163,6 +132,10 @@ class ActionModule(ActionBase): if trim_blocks is not None: self._templar.environment.trim_blocks = bool(trim_blocks) + # add ansible 'template' vars + temp_vars = task_vars.copy() + temp_vars.update(generate_ansible_template_vars(source)) + old_vars = self._templar._available_variables self._templar.set_available_variables(temp_vars) resultant = self._templar.do_template(template_data, preserve_trailing_newlines=True, escape_backslashes=False) diff --git a/lib/ansible/plugins/lookup/template.py b/lib/ansible/plugins/lookup/template.py index e335b9339f3..3b51b377009 100644 --- a/lib/ansible/plugins/lookup/template.py +++ b/lib/ansible/plugins/lookup/template.py @@ -22,6 +22,7 @@ import os from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from ansible.module_utils._text import to_bytes, to_text +from ansible.template import generate_ansible_template_vars try: from __main__ import display @@ -47,8 +48,8 @@ class LookupModule(LookupBase): template_data = to_text(f.read(), errors='surrogate_or_strict') # set jinja2 internal search path for includes - if 'ansible_search_path' in variables: - searchpath = variables['ansible_search_path'] + searchpath = variables.get('ansible_search_path') + if searchpath: # our search paths aren't actually the proper ones for jinja includes. # We want to search into the 'templates' subdir of each search path in # addition to our original search paths. @@ -61,6 +62,11 @@ class LookupModule(LookupBase): searchpath = [self._loader._basedir, os.path.dirname(lookupfile)] self._templar.environment.loader.searchpath = searchpath + # add ansible 'template' vars + temp_vars = variables.copy() + temp_vars.update(generate_ansible_template_vars(lookupfile)) + self._templar.set_available_variables(temp_vars) + # do the templating res = self._templar.template(template_data, preserve_trailing_newlines=True,convert_data=convert_data_p) ret.append(res) diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py index 38119742a4f..e0de47a8acb 100644 --- a/lib/ansible/template/__init__.py +++ b/lib/ansible/template/__init__.py @@ -21,8 +21,11 @@ __metaclass__ = type import ast import contextlib +import datetime import os +import pwd import re +import time from io import StringIO from numbers import Number @@ -35,13 +38,13 @@ except ImportError: from jinja2 import Environment from jinja2.loaders import FileSystemLoader from jinja2.exceptions import TemplateSyntaxError, UndefinedError -from jinja2.utils import concat as j2_concat, missing +from jinja2.utils import concat as j2_concat from jinja2.runtime import Context, StrictUndefined from ansible import constants as C from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable from ansible.module_utils.six import string_types, text_type -from ansible.module_utils._text import to_native, to_text +from ansible.module_utils._text import to_native, to_text, to_bytes from ansible.plugins import filter_loader, lookup_loader, test_loader from ansible.template.safe_eval import safe_eval from ansible.template.template import AnsibleJ2Template @@ -54,7 +57,7 @@ except ImportError: display = Display() -__all__ = ['Templar'] +__all__ = ['Templar', 'generate_ansible_template_vars'] # A regex for checking to see if a variable we're trying to # expand is just a single variable name. @@ -65,6 +68,33 @@ NON_TEMPLATED_TYPES = ( bool, Number ) JINJA2_OVERRIDE = '#jinja2:' +def generate_ansible_template_vars(path): + + b_path = to_bytes(path) + try: + template_uid = pwd.getpwuid(os.stat(b_path).st_uid).pw_name + except: + template_uid = os.stat(b_path).st_uid + + temp_vars = {} + temp_vars['template_host'] = os.uname()[1] + temp_vars['template_path'] = b_path + temp_vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(b_path)) + temp_vars['template_uid'] = template_uid + temp_vars['template_fullpath'] = os.path.abspath(path) + temp_vars['template_run_date'] = datetime.datetime.now() + + managed_default = C.DEFAULT_MANAGED_STR + managed_str = managed_default.format( + host = temp_vars['template_host'], + uid = temp_vars['template_uid'], + file = temp_vars['template_path'], + ) + temp_vars['ansible_managed'] = time.strftime( managed_str, time.localtime(os.path.getmtime(b_path))) + + return temp_vars + + def _escape_backslashes(data, jinja_env): """Double backslashes within jinja2 expressions