2012-10-26 01:18:08 +00:00
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import codecs
import jinja2
2013-04-10 20:45:53 +00:00
from jinja2 . runtime import StrictUndefined
2012-10-26 01:18:08 +00:00
import yaml
import json
from ansible import errors
import ansible . constants as C
import time
import subprocess
import datetime
import pwd
2013-08-02 01:08:23 +00:00
import ast
2012-10-26 01:18:08 +00:00
2013-04-20 13:51:20 +00:00
class Globals ( object ) :
2013-05-11 21:22:56 +00:00
2013-04-20 13:51:20 +00:00
FILTERS = None
2013-05-11 21:22:56 +00:00
2013-04-20 13:51:20 +00:00
def __init__ ( self ) :
2013-06-18 17:24:30 +00:00
pass
2013-04-20 13:51:20 +00:00
def _get_filters ( ) :
2013-05-11 21:22:56 +00:00
''' return filter plugin instances '''
2013-04-20 13:51:20 +00:00
2013-05-11 21:22:56 +00:00
if Globals . FILTERS is not None :
return Globals . FILTERS
2013-04-20 13:51:20 +00:00
2013-05-11 21:22:56 +00:00
from ansible import utils
plugins = [ x for x in utils . plugins . filter_loader . all ( ) ]
filters = { }
for fp in plugins :
filters . update ( fp . filters ( ) )
Globals . FILTERS = filters
2013-06-18 17:24:30 +00:00
2013-05-11 21:22:56 +00:00
return Globals . FILTERS
2013-04-10 21:52:35 +00:00
2013-04-28 13:20:43 +00:00
def _get_extensions ( ) :
''' return jinja2 extensions to load '''
'''
if some extensions are set via jinja_extensions in ansible . cfg , we try
to load them with the jinja environment
'''
jinja_exts = [ ]
if C . DEFAULT_JINJA2_EXTENSIONS :
'''
Let ' s make sure the configuration directive doesn ' t contain spaces
and split extensions in an array
'''
jinja_exts = C . DEFAULT_JINJA2_EXTENSIONS . replace ( " " , " " ) . split ( ' , ' )
return jinja_exts
2013-04-10 21:52:35 +00:00
class Flags :
2013-04-10 23:12:10 +00:00
LEGACY_TEMPLATE_WARNING = False
2013-04-10 21:52:35 +00:00
2012-10-26 01:18:08 +00:00
# TODO: refactor this file
2013-04-09 20:38:24 +00:00
FILTER_PLUGINS = None
2012-10-26 01:18:08 +00:00
_LISTRE = re . compile ( r " ( \ w+) \ [( \ d+) \ ] " )
2012-11-19 14:48:16 +00:00
JINJA2_OVERRIDE = ' #jinja2: '
2012-10-26 01:18:08 +00:00
2013-04-10 23:19:01 +00:00
def lookup ( name , * args , * * kwargs ) :
2013-04-16 22:50:00 +00:00
from ansible import utils
2013-04-10 23:19:01 +00:00
instance = utils . plugins . lookup_loader . get ( name . lower ( ) , basedir = kwargs . get ( ' basedir ' , None ) )
2013-05-19 23:26:04 +00:00
vars = kwargs . get ( ' vars ' , None )
2013-06-01 22:15:38 +00:00
2013-04-10 23:19:01 +00:00
if instance is not None :
2013-05-19 23:26:04 +00:00
ran = instance . run ( * args , inject = vars , * * kwargs )
return " , " . join ( ran )
2013-04-10 23:19:01 +00:00
else :
raise errors . AnsibleError ( " lookup plugin ( %s ) not found " % name )
2013-04-10 21:52:35 +00:00
def _legacy_varFindLimitSpace ( basedir , vars , space , part , lookup_fatal , depth , expand_lists ) :
2012-11-12 23:08:10 +00:00
''' limits the search space of space to part
2013-06-18 17:24:30 +00:00
2012-11-12 23:08:10 +00:00
basically does space . get ( part , None ) , but with
templating for part and a few more things
'''
2012-10-26 01:18:08 +00:00
2012-11-12 23:08:10 +00:00
# Previous part couldn't be found, nothing to limit to
2012-10-26 01:18:08 +00:00
if space is None :
return space
2012-11-12 23:08:10 +00:00
# A part with escaped .s in it is compounded by { and }, remove them
2012-10-26 01:18:08 +00:00
if part [ 0 ] == ' { ' and part [ - 1 ] == ' } ' :
part = part [ 1 : - 1 ]
2012-11-12 23:08:10 +00:00
# Template part to resolve variables within (${var$var2})
2013-04-10 21:52:35 +00:00
part = legacy_varReplace ( basedir , part , vars , lookup_fatal = lookup_fatal , depth = depth + 1 , expand_lists = expand_lists )
2012-11-12 23:08:10 +00:00
# Now find it
2012-10-26 01:18:08 +00:00
if part in space :
space = space [ part ]
elif " [ " in part :
m = _LISTRE . search ( part )
if not m :
return None
else :
try :
space = space [ m . group ( 1 ) ] [ int ( m . group ( 2 ) ) ]
except ( KeyError , IndexError ) :
return None
else :
return None
2012-11-12 23:08:10 +00:00
2013-01-09 12:41:40 +00:00
# if space is a string, check if it's a reference to another variable
if isinstance ( space , basestring ) :
2013-02-08 19:55:55 +00:00
space = template ( basedir , space , vars , lookup_fatal = lookup_fatal , depth = depth + 1 , expand_lists = expand_lists )
2013-01-09 12:41:40 +00:00
2012-10-26 01:18:08 +00:00
return space
2013-04-10 21:52:35 +00:00
def _legacy_varFind ( basedir , text , vars , lookup_fatal , depth , expand_lists ) :
2012-11-12 23:08:10 +00:00
''' Searches for a variable in text and finds its replacement in vars
The variables can have two formats ;
- simple , $ followed by alphanumerics and / or underscores
- complex , $ { followed by alphanumerics , underscores , periods , braces and brackets , ended by a }
Examples :
- $ variable : simple variable that will have vars [ ' variable ' ] as its replacement
- $ { variable . complex } : complex variable that will have vars [ ' variable ' ] [ ' complex ' ] as its replacement
- $ variable . complex : simple variable , identical to the first , . complex ignored
Complex variables are broken into parts by separating on periods , except if enclosed in { } .
$ { variable . { fully . qualified . domain } } would be parsed as two parts , variable and fully . qualified . domain ,
whereas $ { variable . fully . qualified . domain } would be parsed as four parts .
2012-10-26 01:18:08 +00:00
2012-11-12 23:08:10 +00:00
Returns a dict ( replacement = < value in vars > , start = < index into text where the variable stated > ,
end = < index into text where the variable ends > )
or None if no variable could be found in text . If replacement is None , it should be replaced with the
original data in the caller .
'''
2012-10-26 01:18:08 +00:00
2013-05-06 13:48:52 +00:00
# short circuit this whole function if we have specified we don't want
# legacy var replacement
2013-09-26 03:22:09 +00:00
if C . DEFAULT_LEGACY_PLAYBOOK_VARIABLES == False :
2013-05-06 13:48:52 +00:00
return None
2012-10-26 01:18:08 +00:00
start = text . find ( " $ " )
if start == - 1 :
return None
# $ as last character
if start + 1 == len ( text ) :
return None
# Escaped var
if start > 0 and text [ start - 1 ] == ' \\ ' :
return { ' replacement ' : ' $ ' , ' start ' : start - 1 , ' end ' : start + 1 }
var_start = start + 1
if text [ var_start ] == ' { ' :
is_complex = True
brace_level = 1
var_start + = 1
else :
is_complex = False
2012-11-13 01:03:16 +00:00
brace_level = 1
2013-02-10 03:35:27 +00:00
2012-11-13 01:03:16 +00:00
# is_lookup is true for $FILE(...) and friends
is_lookup = False
lookup_plugin_name = None
2012-10-26 01:18:08 +00:00
end = var_start
2013-02-10 03:35:27 +00:00
2012-11-13 01:03:16 +00:00
# part_start is an index of where the current part started
part_start = var_start
2012-10-26 01:18:08 +00:00
space = vars
2013-02-10 03:35:27 +00:00
2012-11-13 01:03:16 +00:00
while end < len ( text ) and ( ( ( is_lookup or is_complex ) and brace_level > 0 ) or ( not is_complex and not is_lookup ) ) :
2013-02-10 03:35:27 +00:00
2012-10-26 01:18:08 +00:00
if text [ end ] . isalnum ( ) or text [ end ] == ' _ ' :
pass
2012-11-13 01:03:16 +00:00
elif not is_complex and not is_lookup and text [ end ] == ' ( ' and text [ part_start : end ] . isupper ( ) :
is_lookup = True
lookup_plugin_name = text [ part_start : end ]
part_start = end + 1
elif is_lookup and text [ end ] == ' ( ' :
brace_level + = 1
elif is_lookup and text [ end ] == ' ) ' :
brace_level - = 1
elif is_lookup :
# lookups are allowed arbitrary contents
pass
2012-10-26 01:18:08 +00:00
elif is_complex and text [ end ] == ' { ' :
brace_level + = 1
elif is_complex and text [ end ] == ' } ' :
brace_level - = 1
2013-02-25 14:09:44 +00:00
elif is_complex and text [ end ] in ( ' $ ' , ' [ ' , ' ] ' , ' - ' ) :
2012-10-26 01:18:08 +00:00
pass
elif is_complex and text [ end ] == ' . ' :
2012-11-13 01:03:16 +00:00
if brace_level == 1 :
2013-04-10 21:52:35 +00:00
space = _legacy_varFindLimitSpace ( basedir , vars , space , text [ part_start : end ] , lookup_fatal , depth , expand_lists )
2012-11-13 01:03:16 +00:00
part_start = end + 1
2012-10-26 01:18:08 +00:00
else :
2012-11-13 01:03:16 +00:00
# This breaks out of the loop on non-variable name characters
2012-10-26 01:18:08 +00:00
break
end + = 1
2013-02-10 03:35:27 +00:00
2012-10-26 01:18:08 +00:00
var_end = end
2013-02-10 03:35:27 +00:00
2012-11-13 01:03:16 +00:00
# Handle "This has $ in it"
if var_end == part_start :
return { ' replacement ' : None , ' start ' : start , ' end ' : end }
# Handle lookup plugins
if is_lookup :
# When basedir is None, handle lookup plugins later
if basedir is None :
return { ' replacement ' : None , ' start ' : start , ' end ' : end }
var_end - = 1
2013-02-18 00:40:38 +00:00
from ansible import utils
2012-11-13 01:03:16 +00:00
args = text [ part_start : var_end ]
if lookup_plugin_name == ' LOOKUP ' :
lookup_plugin_name , args = args . split ( " , " , 1 )
args = args . strip ( )
2012-11-14 10:16:53 +00:00
# args have to be templated
2013-04-10 23:09:57 +00:00
args = legacy_varReplace ( basedir , args , vars , lookup_fatal , depth + 1 , True )
2013-04-12 22:44:40 +00:00
if isinstance ( args , basestring ) and args . find ( ' $ ' ) != - 1 :
2013-05-11 21:24:12 +00:00
# unable to evaluate something like $FILE($item) at this point, try to evaluate later
return None
2013-04-12 22:44:40 +00:00
2013-04-10 23:09:57 +00:00
2012-11-13 01:03:16 +00:00
instance = utils . plugins . lookup_loader . get ( lookup_plugin_name . lower ( ) , basedir = basedir )
if instance is not None :
2012-12-19 18:10:24 +00:00
try :
replacement = instance . run ( args , inject = vars )
2013-02-25 21:26:16 +00:00
if expand_lists :
2013-04-06 20:00:12 +00:00
replacement = " , " . join ( [ unicode ( x ) for x in replacement ] )
2013-02-27 09:08:45 +00:00
except :
2012-12-19 18:10:24 +00:00
if not lookup_fatal :
replacement = None
2013-01-29 09:31:33 +00:00
else :
raise
2013-04-10 23:09:57 +00:00
2012-11-13 01:03:16 +00:00
else :
replacement = None
2013-05-20 00:05:04 +00:00
return dict ( replacement = replacement , start = start , end = end )
2012-11-13 01:03:16 +00:00
2012-10-26 01:18:08 +00:00
if is_complex :
var_end - = 1
if text [ var_end ] != ' } ' or brace_level != 0 :
return None
2013-04-10 21:52:35 +00:00
space = _legacy_varFindLimitSpace ( basedir , vars , space , text [ part_start : var_end ] , lookup_fatal , depth , expand_lists )
2013-05-20 00:05:04 +00:00
return dict ( replacement = space , start = start , end = end )
2012-10-26 01:18:08 +00:00
2013-04-10 21:52:35 +00:00
def legacy_varReplace ( basedir , raw , vars , lookup_fatal = True , depth = 0 , expand_lists = False ) :
2012-10-26 01:18:08 +00:00
''' Perform variable replacement of $variables in string raw using vars dictionary '''
# this code originally from yum
2013-02-02 11:29:28 +00:00
if not isinstance ( raw , unicode ) :
raw = raw . decode ( " utf-8 " )
2012-10-26 01:18:08 +00:00
if ( depth > 20 ) :
raise errors . AnsibleError ( " template recursion depth exceeded " )
done = [ ] # Completed chunks to return
while raw :
2013-04-10 21:52:35 +00:00
m = _legacy_varFind ( basedir , raw , vars , lookup_fatal , depth , expand_lists )
2012-10-26 01:18:08 +00:00
if not m :
done . append ( raw )
break
# Determine replacement value (if unknown variable then preserve
# original)
replacement = m [ ' replacement ' ]
if expand_lists and isinstance ( replacement , ( list , tuple ) ) :
2013-03-12 04:01:45 +00:00
replacement = " , " . join ( [ str ( x ) for x in replacement ] )
2012-10-26 01:18:08 +00:00
if isinstance ( replacement , ( str , unicode ) ) :
2013-04-10 23:09:57 +00:00
replacement = legacy_varReplace ( basedir , replacement , vars , lookup_fatal , depth = depth + 1 , expand_lists = expand_lists )
2012-10-26 01:18:08 +00:00
if replacement is None :
replacement = raw [ m [ ' start ' ] : m [ ' end ' ] ]
start , end = m [ ' start ' ] , m [ ' end ' ]
done . append ( raw [ : start ] ) # Keep stuff leading up to token
done . append ( unicode ( replacement ) ) # Append replacement value
raw = raw [ end : ] # Continue with remainder of string
2013-10-11 22:37:39 +00:00
result = ' ' . join ( done )
if result != raw :
2013-10-11 23:04:26 +00:00
from ansible import utils
2013-10-11 22:37:39 +00:00
utils . deprecated ( " Legacy variable subsitution, such as using $ {foo} or $foo instead of {{ foo }} is currently valid but will be phased out and has been out of favor since version 1.2. This is the last of legacy features on our deprecation list. You may continue to use this if you have specific needs for now " , " 1.6 " )
return result
2012-10-26 01:18:08 +00:00
2013-04-26 01:10:54 +00:00
# TODO: varname is misnamed here
2013-07-07 17:18:32 +00:00
def template ( basedir , varname , vars , lookup_fatal = True , depth = 0 , expand_lists = True , convert_bare = False , fail_on_undefined = False , filter_fatal = True ) :
2012-11-09 14:43:15 +00:00
''' templates a data structure by traversing it and substituting for other data structures '''
2012-10-26 01:18:08 +00:00
2013-07-07 17:18:32 +00:00
try :
if convert_bare and isinstance ( varname , basestring ) :
first_part = varname . split ( " . " ) [ 0 ] . split ( " [ " ) [ 0 ]
if first_part in vars and ' {{ ' not in varname and ' $ ' not in varname :
varname = " {{ %s }} " % varname
if isinstance ( varname , basestring ) :
if ' {{ ' in varname or ' { % ' in varname :
varname = template_from_string ( basedir , varname , vars , fail_on_undefined )
if not ' $ ' in varname :
return varname
m = _legacy_varFind ( basedir , varname , vars , lookup_fatal , depth , expand_lists )
if not m :
2012-11-01 17:52:13 +00:00
return varname
2013-07-07 17:18:32 +00:00
if m [ ' start ' ] == 0 and m [ ' end ' ] == len ( varname ) :
if m [ ' replacement ' ] is not None :
Flags . LEGACY_TEMPLATE_WARNING = True
return template ( basedir , m [ ' replacement ' ] , vars , lookup_fatal , depth , expand_lists )
else :
return varname
else :
Flags . LEGACY_TEMPLATE_WARNING = True
return legacy_varReplace ( basedir , varname , vars , lookup_fatal , depth , expand_lists )
elif isinstance ( varname , ( list , tuple ) ) :
2013-07-22 13:21:55 +00:00
return [ template ( basedir , v , vars , lookup_fatal , depth , expand_lists , fail_on_undefined = fail_on_undefined ) for v in varname ]
2013-07-07 17:18:32 +00:00
elif isinstance ( varname , dict ) :
d = { }
for ( k , v ) in varname . iteritems ( ) :
2013-07-22 13:21:55 +00:00
d [ k ] = template ( basedir , v , vars , lookup_fatal , depth , expand_lists , fail_on_undefined = fail_on_undefined )
2013-07-07 17:18:32 +00:00
return d
2012-10-26 01:18:08 +00:00
else :
2013-07-07 17:18:32 +00:00
return varname
except errors . AnsibleFilterError :
if filter_fatal :
raise
else :
return varname
2012-10-26 01:18:08 +00:00
2013-04-10 23:19:01 +00:00
2012-11-12 14:25:01 +00:00
class _jinja2_vars ( object ) :
2013-01-25 00:48:04 +00:00
'''
Helper class to template all variable content before jinja2 sees it .
This is done by hijacking the variable storage that jinja2 uses , and
overriding __contains__ and __getitem__ to look like a dict . Added bonus
is avoiding duplicating the large hashes that inject tends to be .
To facilitate using builtin jinja2 things like range , globals are handled
here .
2013-06-18 17:24:30 +00:00
extras is a list of locals to also search for variables .
2013-01-25 00:48:04 +00:00
'''
2013-02-18 00:40:38 +00:00
2013-07-22 13:21:55 +00:00
def __init__ ( self , basedir , vars , globals , fail_on_undefined , * extras ) :
2012-11-12 14:25:01 +00:00
self . basedir = basedir
self . vars = vars
2012-12-19 08:42:15 +00:00
self . globals = globals
2013-07-22 13:21:55 +00:00
self . fail_on_undefined = fail_on_undefined
2013-01-25 00:48:04 +00:00
self . extras = extras
2013-02-18 00:40:38 +00:00
2012-11-12 14:25:01 +00:00
def __contains__ ( self , k ) :
2013-01-25 00:48:04 +00:00
if k in self . vars :
return True
for i in self . extras :
if k in i :
return True
if k in self . globals :
return True
return False
2013-02-18 00:40:38 +00:00
2012-11-12 14:25:01 +00:00
def __getitem__ ( self , varname ) :
if varname not in self . vars :
2013-01-25 00:48:04 +00:00
for i in self . extras :
if varname in i :
return i [ varname ]
2012-12-19 08:42:15 +00:00
if varname in self . globals :
return self . globals [ varname ]
else :
raise KeyError ( " undefined variable: %s " % varname )
2012-11-13 10:34:34 +00:00
var = self . vars [ varname ]
# HostVars is special, return it as-is
if isinstance ( var , dict ) and type ( var ) != dict :
return var
else :
2013-07-22 13:21:55 +00:00
return template ( self . basedir , var , self . vars , fail_on_undefined = self . fail_on_undefined )
2013-02-18 00:40:38 +00:00
2013-01-25 00:48:04 +00:00
def add_locals ( self , locals ) :
'''
If locals are provided , create a copy of self containing those
locals in addition to what is already in this variable proxy .
'''
if locals is None :
return self
2013-07-22 13:21:55 +00:00
return _jinja2_vars ( self . basedir , self . vars , self . globals , self . fail_on_undefined , locals , * self . extras )
2013-01-25 00:48:04 +00:00
class J2Template ( jinja2 . environment . Template ) :
'''
This class prevents Jinja2 from running _jinja2_vars through dict ( )
Without this , { % include % } and similar will create new contexts unlike
the special one created in template_from_file . This ensures they are all
alike , with the exception of potential locals .
'''
def new_context ( self , vars = None , shared = False , locals = None ) :
return jinja2 . runtime . Context ( self . environment , vars . add_locals ( locals ) , self . name , self . blocks )
2012-11-12 14:25:01 +00:00
2012-10-26 01:18:08 +00:00
def template_from_file ( basedir , path , vars ) :
''' run a file through the templating engine '''
2013-06-18 17:24:30 +00:00
fail_on_undefined = C . DEFAULT_UNDEFINED_VAR_BEHAVIOR
2012-10-26 01:18:08 +00:00
from ansible import utils
realpath = utils . path_dwim ( basedir , path )
loader = jinja2 . FileSystemLoader ( [ basedir , os . path . dirname ( realpath ) ] )
2013-02-13 09:10:16 +00:00
2013-04-10 23:19:01 +00:00
def my_lookup ( * args , * * kwargs ) :
2013-05-19 23:26:04 +00:00
kwargs [ ' vars ' ] = vars
2013-04-10 23:19:01 +00:00
return lookup ( * args , basedir = basedir , * * kwargs )
2013-04-28 13:20:43 +00:00
environment = jinja2 . Environment ( loader = loader , trim_blocks = True , extensions = _get_extensions ( ) )
2013-04-20 13:51:20 +00:00
environment . filters . update ( _get_filters ( ) )
environment . globals [ ' lookup ' ] = my_lookup
2013-06-18 17:24:30 +00:00
if fail_on_undefined :
environment . undefined = StrictUndefined
2013-04-20 13:51:20 +00:00
2012-10-26 01:18:08 +00:00
try :
data = codecs . open ( realpath , encoding = " utf8 " ) . read ( )
except UnicodeDecodeError :
raise errors . AnsibleError ( " unable to process as utf-8: %s " % realpath )
except :
raise errors . AnsibleError ( " unable to read %s " % realpath )
2012-11-14 07:20:39 +00:00
2013-06-18 17:24:30 +00:00
2013-09-09 19:50:21 +00:00
# Get jinja env overrides from template
2012-11-19 14:48:16 +00:00
if data . startswith ( JINJA2_OVERRIDE ) :
2012-11-14 07:20:39 +00:00
eol = data . find ( ' \n ' )
2012-11-19 14:54:19 +00:00
line = data [ len ( JINJA2_OVERRIDE ) : eol ]
2012-11-14 07:20:39 +00:00
data = data [ eol + 1 : ]
for pair in line . split ( ' , ' ) :
( key , val ) = pair . split ( ' : ' )
2013-08-02 01:08:23 +00:00
setattr ( environment , key . strip ( ) , ast . literal_eval ( val . strip ( ) ) )
2012-11-14 07:20:39 +00:00
2013-01-25 00:48:04 +00:00
environment . template_class = J2Template
2012-10-26 01:18:08 +00:00
t = environment . from_string ( data )
vars = vars . copy ( )
try :
template_uid = pwd . getpwuid ( os . stat ( realpath ) . st_uid ) . pw_name
except :
template_uid = os . stat ( realpath ) . st_uid
vars [ ' template_host ' ] = os . uname ( ) [ 1 ]
vars [ ' template_path ' ] = realpath
vars [ ' template_mtime ' ] = datetime . datetime . fromtimestamp ( os . path . getmtime ( realpath ) )
vars [ ' template_uid ' ] = template_uid
2013-01-04 06:26:11 +00:00
vars [ ' template_fullpath ' ] = os . path . abspath ( realpath )
vars [ ' template_run_date ' ] = datetime . datetime . now ( )
2012-10-26 01:18:08 +00:00
managed_default = C . DEFAULT_MANAGED_STR
managed_str = managed_default . format (
2013-04-10 22:19:31 +00:00
host = vars [ ' template_host ' ] ,
uid = vars [ ' template_uid ' ] ,
file = vars [ ' template_path ' ]
)
vars [ ' ansible_managed ' ] = time . strftime (
managed_str ,
time . localtime ( os . path . getmtime ( realpath ) )
)
2012-10-26 01:18:08 +00:00
2012-11-12 14:25:01 +00:00
# This line performs deep Jinja2 magic that uses the _jinja2_vars object for vars
# Ideally, this could use some API where setting shared=True and the object won't get
# passed through dict(o), but I have not found that yet.
2013-06-18 17:24:30 +00:00
try :
2013-07-22 13:21:55 +00:00
res = jinja2 . utils . concat ( t . root_render_func ( t . new_context ( _jinja2_vars ( basedir , vars , t . globals , fail_on_undefined ) , shared = True ) ) )
2013-06-18 17:24:30 +00:00
except jinja2 . exceptions . UndefinedError , e :
2013-06-18 17:30:02 +00:00
raise errors . AnsibleUndefinedVariable ( " One or more undefined variables: %s " % str ( e ) )
2012-11-12 14:25:01 +00:00
2012-10-26 01:18:08 +00:00
if data . endswith ( ' \n ' ) and not res . endswith ( ' \n ' ) :
res = res + ' \n '
return template ( basedir , res , vars )
2013-06-18 17:24:30 +00:00
def template_from_string ( basedir , data , vars , fail_on_undefined = False ) :
2013-04-28 13:20:43 +00:00
''' run a string through the (Jinja2) templating engine '''
2013-06-18 17:24:30 +00:00
2013-04-05 23:10:32 +00:00
try :
if type ( data ) == str :
data = unicode ( data , ' utf-8 ' )
2013-04-28 13:20:43 +00:00
environment = jinja2 . Environment ( trim_blocks = True , undefined = StrictUndefined , extensions = _get_extensions ( ) )
2013-04-20 13:51:20 +00:00
environment . filters . update ( _get_filters ( ) )
2013-04-06 14:45:09 +00:00
environment . template_class = J2Template
2013-06-01 22:15:38 +00:00
if ' _original_file ' in vars :
basedir = os . path . dirname ( vars [ ' _original_file ' ] )
2013-06-03 13:57:02 +00:00
filesdir = os . path . abspath ( os . path . join ( basedir , ' .. ' , ' files ' ) )
2013-06-01 22:15:38 +00:00
if os . path . exists ( filesdir ) :
basedir = filesdir
2013-04-05 23:10:32 +00:00
# TODO: may need some way of using lookup plugins here seeing we aren't calling
# the legacy engine, lookup() as a function, perhaps?
2013-04-06 13:55:31 +00:00
2013-10-08 12:26:40 +00:00
data = data . decode ( ' utf-8 ' )
2013-04-06 13:55:31 +00:00
try :
t = environment . from_string ( data )
2013-04-23 02:03:39 +00:00
except Exception , e :
if ' recursion ' in str ( e ) :
2013-04-06 13:55:31 +00:00
raise errors . AnsibleError ( " recursive loop detected in template string: %s " % data )
else :
2013-04-06 14:45:09 +00:00
return data
2013-06-18 17:24:30 +00:00
2013-04-10 23:19:01 +00:00
def my_lookup ( * args , * * kwargs ) :
2013-06-10 18:23:48 +00:00
kwargs [ ' vars ' ] = vars
2013-04-10 23:19:01 +00:00
return lookup ( * args , basedir = basedir , * * kwargs )
2013-06-18 17:24:30 +00:00
2013-04-10 23:19:01 +00:00
t . globals [ ' lookup ' ] = my_lookup
2013-06-18 17:24:30 +00:00
2013-10-08 12:26:40 +00:00
jvars = _jinja2_vars ( basedir , vars , t . globals , fail_on_undefined )
new_context = t . new_context ( jvars , shared = True )
rf = t . root_render_func ( new_context )
res = jinja2 . utils . concat ( rf )
2013-04-05 23:10:32 +00:00
return res
2013-07-29 21:33:32 +00:00
except ( jinja2 . exceptions . UndefinedError , errors . AnsibleUndefinedVariable ) :
2013-06-18 17:24:30 +00:00
if fail_on_undefined :
raise
else :
return data
2013-04-03 05:03:30 +00:00