centralize ansible_managed and other template vars

now template lookup supports these again.
This commit is contained in:
Brian Coca 2017-04-07 11:46:28 -04:00 committed by Brian Coca
parent f7566ef1f1
commit 5b7e8a7bd6
3 changed files with 47 additions and 38 deletions

View file

@ -17,17 +17,14 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import datetime
import os import os
import pwd
import time
from ansible import constants as C from ansible import constants as C
from ansible.errors import AnsibleError 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.module_utils._text import to_bytes, to_native, to_text
from ansible.plugins.action import ActionBase from ansible.plugins.action import ActionBase
from ansible.utils.hashing import checksum_s from ansible.utils.hashing import checksum_s
from ansible.template import generate_ansible_template_vars
boolean = C.mk_boolean boolean = C.mk_boolean
@ -110,36 +107,8 @@ class ActionModule(ActionBase):
with open(b_source, 'r') as f: with open(b_source, 'r') as f:
template_data = to_text(f.read()) 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 # set jinja2 internal search path for includes
if 'ansible_search_path' in task_vars: searchpath = task_vars.get('ansible_search_path', [])
searchpath = task_vars['ansible_search_path']
# our search paths aren't actually the proper ones for jinja includes.
searchpath.extend([self._loader._basedir, os.path.dirname(source)]) searchpath.extend([self._loader._basedir, os.path.dirname(source)])
# We want to search into the 'templates' subdir of each search path in # 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: if trim_blocks is not None:
self._templar.environment.trim_blocks = bool(trim_blocks) 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 old_vars = self._templar._available_variables
self._templar.set_available_variables(temp_vars) self._templar.set_available_variables(temp_vars)
resultant = self._templar.do_template(template_data, preserve_trailing_newlines=True, escape_backslashes=False) resultant = self._templar.do_template(template_data, preserve_trailing_newlines=True, escape_backslashes=False)

View file

@ -22,6 +22,7 @@ import os
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase from ansible.plugins.lookup import LookupBase
from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils._text import to_bytes, to_text
from ansible.template import generate_ansible_template_vars
try: try:
from __main__ import display from __main__ import display
@ -47,8 +48,8 @@ class LookupModule(LookupBase):
template_data = to_text(f.read(), errors='surrogate_or_strict') template_data = to_text(f.read(), errors='surrogate_or_strict')
# set jinja2 internal search path for includes # set jinja2 internal search path for includes
if 'ansible_search_path' in variables: searchpath = variables.get('ansible_search_path')
searchpath = variables['ansible_search_path'] if searchpath:
# our search paths aren't actually the proper ones for jinja includes. # 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 # We want to search into the 'templates' subdir of each search path in
# addition to our original search paths. # addition to our original search paths.
@ -61,6 +62,11 @@ class LookupModule(LookupBase):
searchpath = [self._loader._basedir, os.path.dirname(lookupfile)] searchpath = [self._loader._basedir, os.path.dirname(lookupfile)]
self._templar.environment.loader.searchpath = searchpath 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 # do the templating
res = self._templar.template(template_data, preserve_trailing_newlines=True,convert_data=convert_data_p) res = self._templar.template(template_data, preserve_trailing_newlines=True,convert_data=convert_data_p)
ret.append(res) ret.append(res)

View file

@ -21,8 +21,11 @@ __metaclass__ = type
import ast import ast
import contextlib import contextlib
import datetime
import os import os
import pwd
import re import re
import time
from io import StringIO from io import StringIO
from numbers import Number from numbers import Number
@ -35,13 +38,13 @@ except ImportError:
from jinja2 import Environment from jinja2 import Environment
from jinja2.loaders import FileSystemLoader from jinja2.loaders import FileSystemLoader
from jinja2.exceptions import TemplateSyntaxError, UndefinedError 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 jinja2.runtime import Context, StrictUndefined
from ansible import constants as C from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable
from ansible.module_utils.six import string_types, text_type 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.plugins import filter_loader, lookup_loader, test_loader
from ansible.template.safe_eval import safe_eval from ansible.template.safe_eval import safe_eval
from ansible.template.template import AnsibleJ2Template from ansible.template.template import AnsibleJ2Template
@ -54,7 +57,7 @@ except ImportError:
display = Display() display = Display()
__all__ = ['Templar'] __all__ = ['Templar', 'generate_ansible_template_vars']
# A regex for checking to see if a variable we're trying to # A regex for checking to see if a variable we're trying to
# expand is just a single variable name. # expand is just a single variable name.
@ -65,6 +68,33 @@ NON_TEMPLATED_TYPES = ( bool, Number )
JINJA2_OVERRIDE = '#jinja2:' 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): def _escape_backslashes(data, jinja_env):
"""Double backslashes within jinja2 expressions """Double backslashes within jinja2 expressions