PageRenderTime 36ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ansible/utils/template.py

https://gitlab.com/18runt88/ansible
Python | 404 lines | 304 code | 37 blank | 63 comment | 65 complexity | aa9224224b8133390592a6ef81dcfc25 MD5 | raw file
  1. # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
  2. #
  3. # This file is part of Ansible
  4. #
  5. # Ansible is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # Ansible is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  17. import os
  18. import re
  19. import codecs
  20. import jinja2
  21. from jinja2.runtime import StrictUndefined
  22. from jinja2.exceptions import TemplateSyntaxError
  23. import yaml
  24. import json
  25. from ansible import errors
  26. import ansible.constants as C
  27. import time
  28. import subprocess
  29. import datetime
  30. import pwd
  31. import ast
  32. import traceback
  33. from numbers import Number
  34. from ansible.utils.string_functions import count_newlines_from_end
  35. from ansible.utils import to_bytes, to_unicode
  36. class Globals(object):
  37. FILTERS = None
  38. def __init__(self):
  39. pass
  40. def _get_filters():
  41. ''' return filter plugin instances '''
  42. if Globals.FILTERS is not None:
  43. return Globals.FILTERS
  44. from ansible import utils
  45. plugins = [ x for x in utils.plugins.filter_loader.all()]
  46. filters = {}
  47. for fp in plugins:
  48. filters.update(fp.filters())
  49. Globals.FILTERS = filters
  50. return Globals.FILTERS
  51. def _get_extensions():
  52. ''' return jinja2 extensions to load '''
  53. '''
  54. if some extensions are set via jinja_extensions in ansible.cfg, we try
  55. to load them with the jinja environment
  56. '''
  57. jinja_exts = []
  58. if C.DEFAULT_JINJA2_EXTENSIONS:
  59. '''
  60. Let's make sure the configuration directive doesn't contain spaces
  61. and split extensions in an array
  62. '''
  63. jinja_exts = C.DEFAULT_JINJA2_EXTENSIONS.replace(" ", "").split(',')
  64. return jinja_exts
  65. class Flags:
  66. LEGACY_TEMPLATE_WARNING = False
  67. # TODO: refactor this file
  68. FILTER_PLUGINS = None
  69. _LISTRE = re.compile(r"(\w+)\[(\d+)\]")
  70. # A regex for checking to see if a variable we're trying to
  71. # expand is just a single variable name.
  72. SINGLE_VAR = re.compile(r"^{{\s*(\w*)\s*}}$")
  73. JINJA2_OVERRIDE = '#jinja2:'
  74. JINJA2_ALLOWED_OVERRIDES = ['trim_blocks', 'lstrip_blocks', 'newline_sequence', 'keep_trailing_newline']
  75. def lookup(name, *args, **kwargs):
  76. from ansible import utils
  77. instance = utils.plugins.lookup_loader.get(name.lower(), basedir=kwargs.get('basedir',None))
  78. tvars = kwargs.get('vars', None)
  79. wantlist = kwargs.pop('wantlist', False)
  80. if instance is not None:
  81. try:
  82. ran = instance.run(*args, inject=tvars, **kwargs)
  83. except errors.AnsibleError:
  84. raise
  85. except jinja2.exceptions.UndefinedError, e:
  86. raise errors.AnsibleUndefinedVariable("One or more undefined variables: %s" % str(e))
  87. except Exception, e:
  88. raise errors.AnsibleError('Unexpected error in during lookup: %s' % e)
  89. if ran and not wantlist:
  90. ran = ",".join(ran)
  91. return ran
  92. else:
  93. raise errors.AnsibleError("lookup plugin (%s) not found" % name)
  94. def template(basedir, varname, templatevars, lookup_fatal=True, depth=0, expand_lists=True, convert_bare=False, fail_on_undefined=False, filter_fatal=True):
  95. ''' templates a data structure by traversing it and substituting for other data structures '''
  96. from ansible import utils
  97. try:
  98. if convert_bare and isinstance(varname, basestring):
  99. first_part = varname.split(".")[0].split("[")[0]
  100. if first_part in templatevars and '{{' not in varname and '$' not in varname:
  101. varname = "{{%s}}" % varname
  102. if isinstance(varname, basestring):
  103. if '{{' in varname or '{%' in varname:
  104. try:
  105. varname = template_from_string(basedir, varname, templatevars, fail_on_undefined)
  106. except errors.AnsibleError, e:
  107. raise errors.AnsibleError("Failed to template %s: %s" % (varname, str(e)))
  108. # template_from_string may return non strings for the case where the var is just
  109. # a reference to a single variable, so we should re_check before we do further evals
  110. if isinstance(varname, basestring):
  111. if (varname.startswith("{") and not varname.startswith("{{")) or varname.startswith("["):
  112. eval_results = utils.safe_eval(varname, locals=templatevars, include_exceptions=True)
  113. if eval_results[1] is None:
  114. varname = eval_results[0]
  115. return varname
  116. elif isinstance(varname, (list, tuple)):
  117. return [template(basedir, v, templatevars, lookup_fatal, depth, expand_lists, convert_bare, fail_on_undefined, filter_fatal) for v in varname]
  118. elif isinstance(varname, dict):
  119. d = {}
  120. for (k, v) in varname.iteritems():
  121. d[k] = template(basedir, v, templatevars, lookup_fatal, depth, expand_lists, convert_bare, fail_on_undefined, filter_fatal)
  122. return d
  123. else:
  124. return varname
  125. except errors.AnsibleFilterError:
  126. if filter_fatal:
  127. raise
  128. else:
  129. return varname
  130. class _jinja2_vars(object):
  131. '''
  132. Helper class to template all variable content before jinja2 sees it.
  133. This is done by hijacking the variable storage that jinja2 uses, and
  134. overriding __contains__ and __getitem__ to look like a dict. Added bonus
  135. is avoiding duplicating the large hashes that inject tends to be.
  136. To facilitate using builtin jinja2 things like range, globals are handled
  137. here.
  138. extras is a list of locals to also search for variables.
  139. '''
  140. def __init__(self, basedir, vars, globals, fail_on_undefined, *extras):
  141. self.basedir = basedir
  142. self.vars = vars
  143. self.globals = globals
  144. self.fail_on_undefined = fail_on_undefined
  145. self.extras = extras
  146. def __contains__(self, k):
  147. if k in self.vars:
  148. return True
  149. for i in self.extras:
  150. if k in i:
  151. return True
  152. if k in self.globals:
  153. return True
  154. return False
  155. def __getitem__(self, varname):
  156. from ansible.runner import HostVars
  157. if varname not in self.vars:
  158. for i in self.extras:
  159. if varname in i:
  160. return i[varname]
  161. if varname in self.globals:
  162. return self.globals[varname]
  163. else:
  164. raise KeyError("undefined variable: %s" % varname)
  165. var = self.vars[varname]
  166. # HostVars is special, return it as-is, as is the special variable
  167. # 'vars', which contains the vars structure
  168. var = to_unicode(var, nonstring="passthru")
  169. if isinstance(var, dict) and varname == "vars" or isinstance(var, HostVars):
  170. return var
  171. else:
  172. return template(self.basedir, var, self.vars, fail_on_undefined=self.fail_on_undefined)
  173. def add_locals(self, locals):
  174. '''
  175. If locals are provided, create a copy of self containing those
  176. locals in addition to what is already in this variable proxy.
  177. '''
  178. if locals is None:
  179. return self
  180. return _jinja2_vars(self.basedir, self.vars, self.globals, self.fail_on_undefined, locals, *self.extras)
  181. class J2Template(jinja2.environment.Template):
  182. '''
  183. This class prevents Jinja2 from running _jinja2_vars through dict()
  184. Without this, {% include %} and similar will create new contexts unlike
  185. the special one created in template_from_file. This ensures they are all
  186. alike, except for potential locals.
  187. '''
  188. def new_context(self, vars=None, shared=False, locals=None):
  189. return jinja2.runtime.Context(self.environment, vars.add_locals(locals), self.name, self.blocks)
  190. def template_from_file(basedir, path, vars, vault_password=None):
  191. ''' run a file through the templating engine '''
  192. fail_on_undefined = C.DEFAULT_UNDEFINED_VAR_BEHAVIOR
  193. from ansible import utils
  194. realpath = utils.path_dwim(basedir, path)
  195. loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
  196. def my_lookup(*args, **kwargs):
  197. kwargs['vars'] = vars
  198. return lookup(*args, basedir=basedir, **kwargs)
  199. def my_finalize(thing):
  200. return thing if thing is not None else ''
  201. environment = jinja2.Environment(loader=loader, trim_blocks=True, extensions=_get_extensions())
  202. environment.filters.update(_get_filters())
  203. environment.globals['lookup'] = my_lookup
  204. environment.globals['finalize'] = my_finalize
  205. if fail_on_undefined:
  206. environment.undefined = StrictUndefined
  207. try:
  208. data = codecs.open(realpath, encoding="utf8").read()
  209. except UnicodeDecodeError:
  210. raise errors.AnsibleError("unable to process as utf-8: %s" % realpath)
  211. except:
  212. raise errors.AnsibleError("unable to read %s" % realpath)
  213. # Get jinja env overrides from template
  214. if data.startswith(JINJA2_OVERRIDE):
  215. eol = data.find('\n')
  216. line = data[len(JINJA2_OVERRIDE):eol]
  217. data = data[eol+1:]
  218. for pair in line.split(','):
  219. (key,val) = pair.split(':')
  220. key = key.strip()
  221. if key in JINJA2_ALLOWED_OVERRIDES:
  222. setattr(environment, key, ast.literal_eval(val.strip()))
  223. environment.template_class = J2Template
  224. try:
  225. t = environment.from_string(data)
  226. except TemplateSyntaxError, e:
  227. # Throw an exception which includes a more user friendly error message
  228. values = {'name': realpath, 'lineno': e.lineno, 'error': str(e)}
  229. msg = 'file: %(name)s, line number: %(lineno)s, error: %(error)s' % \
  230. values
  231. error = errors.AnsibleError(msg)
  232. raise error
  233. vars = vars.copy()
  234. try:
  235. template_uid = pwd.getpwuid(os.stat(realpath).st_uid).pw_name
  236. except:
  237. template_uid = os.stat(realpath).st_uid
  238. vars['template_host'] = os.uname()[1]
  239. vars['template_path'] = realpath
  240. vars['template_mtime'] = datetime.datetime.fromtimestamp(os.path.getmtime(realpath))
  241. vars['template_uid'] = template_uid
  242. vars['template_fullpath'] = os.path.abspath(realpath)
  243. vars['template_run_date'] = datetime.datetime.now()
  244. managed_default = C.DEFAULT_MANAGED_STR
  245. managed_str = managed_default.format(
  246. host = vars['template_host'],
  247. uid = vars['template_uid'],
  248. file = to_bytes(vars['template_path'])
  249. )
  250. vars['ansible_managed'] = time.strftime(
  251. managed_str,
  252. time.localtime(os.path.getmtime(realpath))
  253. )
  254. # This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars
  255. # Ideally, this could use some API where setting shared=True and the object won't get
  256. # passed through dict(o), but I have not found that yet.
  257. try:
  258. res = jinja2.utils.concat(t.root_render_func(t.new_context(_jinja2_vars(basedir, vars, t.globals, fail_on_undefined), shared=True)))
  259. except jinja2.exceptions.UndefinedError, e:
  260. raise errors.AnsibleUndefinedVariable("One or more undefined variables: %s" % str(e))
  261. except jinja2.exceptions.TemplateNotFound, e:
  262. # Throw an exception which includes a more user friendly error message
  263. # This likely will happen for included sub-template. Not that besides
  264. # pure "file not found" it may happen due to Jinja2's "security"
  265. # checks on path.
  266. values = {'name': realpath, 'subname': str(e)}
  267. msg = 'file: %(name)s, error: Cannot find/not allowed to load (include) template %(subname)s' % \
  268. values
  269. error = errors.AnsibleError(msg)
  270. raise error
  271. # The low level calls above do not preserve the newline
  272. # characters at the end of the input data, so we use the
  273. # calculate the difference in newlines and append them
  274. # to the resulting output for parity
  275. res_newlines = count_newlines_from_end(res)
  276. data_newlines = count_newlines_from_end(data)
  277. if data_newlines > res_newlines:
  278. res += '\n' * (data_newlines - res_newlines)
  279. if isinstance(res, unicode):
  280. # do not try to re-template a unicode string
  281. result = res
  282. else:
  283. result = template(basedir, res, vars)
  284. return result
  285. def template_from_string(basedir, data, vars, fail_on_undefined=False):
  286. ''' run a string through the (Jinja2) templating engine '''
  287. try:
  288. if type(data) == str:
  289. data = unicode(data, 'utf-8')
  290. # Check to see if the string we are trying to render is just referencing a single
  291. # var. In this case we don't want to accidentally change the type of the variable
  292. # to a string by using the jinja template renderer. We just want to pass it.
  293. only_one = SINGLE_VAR.match(data)
  294. if only_one:
  295. var_name = only_one.group(1)
  296. if var_name in vars:
  297. resolved_val = vars[var_name]
  298. if isinstance(resolved_val, (bool, Number)):
  299. return resolved_val
  300. def my_finalize(thing):
  301. return thing if thing is not None else ''
  302. environment = jinja2.Environment(trim_blocks=True, undefined=StrictUndefined, extensions=_get_extensions(), finalize=my_finalize)
  303. environment.filters.update(_get_filters())
  304. environment.template_class = J2Template
  305. if '_original_file' in vars:
  306. basedir = os.path.dirname(vars['_original_file'])
  307. filesdir = os.path.abspath(os.path.join(basedir, '..', 'files'))
  308. if os.path.exists(filesdir):
  309. basedir = filesdir
  310. # 6227
  311. if isinstance(data, unicode):
  312. try:
  313. data = data.decode('utf-8')
  314. except UnicodeEncodeError, e:
  315. pass
  316. try:
  317. t = environment.from_string(data)
  318. except TemplateSyntaxError, e:
  319. raise errors.AnsibleError("template error while templating string: %s" % str(e))
  320. except Exception, e:
  321. if 'recursion' in str(e):
  322. raise errors.AnsibleError("recursive loop detected in template string: %s" % data)
  323. else:
  324. return data
  325. def my_lookup(*args, **kwargs):
  326. kwargs['vars'] = vars
  327. return lookup(*args, basedir=basedir, **kwargs)
  328. t.globals['lookup'] = my_lookup
  329. t.globals['finalize'] = my_finalize
  330. jvars =_jinja2_vars(basedir, vars, t.globals, fail_on_undefined)
  331. new_context = t.new_context(jvars, shared=True)
  332. rf = t.root_render_func(new_context)
  333. try:
  334. res = jinja2.utils.concat(rf)
  335. except TypeError, te:
  336. if 'StrictUndefined' in str(te):
  337. raise errors.AnsibleUndefinedVariable(
  338. "Unable to look up a name or access an attribute in template string. " + \
  339. "Make sure your variable name does not contain invalid characters like '-'."
  340. )
  341. else:
  342. raise errors.AnsibleError("an unexpected type error occurred. Error was %s" % te)
  343. return res
  344. except (jinja2.exceptions.UndefinedError, errors.AnsibleUndefinedVariable):
  345. if fail_on_undefined:
  346. raise
  347. else:
  348. return data