def setUp(self): self.test_vars = dict( foo="bar", bam="{{foo}}", num=1, var_true=True, var_false=False, var_dict=dict(a="b"), bad_dict="{a='b'", var_list=[1], recursive="{{recursive}}", some_var="blip", some_static_var="static_blip", some_keyword="{{ foo }}", some_unsafe_var=wrap_var("unsafe_blip"), some_static_unsafe_var=wrap_var("static_unsafe_blip"), some_unsafe_keyword=wrap_var("{{ foo }}"), str_with_error="{{ 'str' | from_json }}", ) self.fake_loader = DictDataLoader({ "/path/to/my_file.txt": "foo\n", }) self.templar = Templar(loader=self.fake_loader, variables=self.test_vars) self._assible_context = AssibleContext(self.templar.environment, {}, {}, {})
def test_resolve_unsafe_list(self): context = self._context( variables={'some_unsafe_key': [wrap_var('some unsafe string 1')]}) res = context.resolve('some_unsafe_key') # self.assertIsInstance(res[0], AssibleUnsafe) self.assertTrue( self.is_unsafe(res), 'return of AssibleContext.resolve (%s) was expected to be marked unsafe but was not' % res)
def test_resolve_unsafe_dict(self): context = self._context( variables={ 'some_unsafe_key': { 'an_unsafe_dict': wrap_var('some unsafe string 1') } }) res = context.resolve('some_unsafe_key') self.assertTrue( self.is_unsafe(res['an_unsafe_dict']), 'return of AssibleContext.resolve (%s) was expected to be marked unsafe but was not' % res['an_unsafe_dict'])
def object_hook(self, pairs): for key in pairs: value = pairs[key] if key == '__assible_vault': value = AssibleVaultEncryptedUnicode(value) if self._vaults: value.vault = self._vaults['default'] return value elif key == '__assible_unsafe': return wrap_var(value) return pairs
def do_var_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None, unsafe=None): result = None if sys.__stdin__.isatty(): do_prompt = self.prompt if prompt and default is not None: msg = "%s [%s]: " % (prompt, default) elif prompt: msg = "%s: " % prompt else: msg = 'input for %s: ' % varname if confirm: while True: result = do_prompt(msg, private) second = do_prompt("confirm " + msg, private) if result == second: break self.display("***** VALUES ENTERED DO NOT MATCH ****") else: result = do_prompt(msg, private) else: result = None self.warning("Not prompting as we are not in interactive mode") # if result is false and default is not None if not result and default is not None: result = default if encrypt: # Circular import because encrypt needs a display class from assible.utils.encrypt import do_encrypt result = do_encrypt(result, encrypt, salt_size, salt) # handle utf-8 chars result = to_text(result, errors='surrogate_or_strict') if unsafe: result = wrap_var(result) return result
def test_wrap_var_no_ref(): thing = { 'foo': { 'bar': 'baz' }, 'bar': ['baz', 'qux'], 'baz': ('qux',), 'none': None, 'text': 'text', } wrapped_thing = wrap_var(thing) thing is not wrapped_thing thing['foo'] is not wrapped_thing['foo'] thing['bar'][0] is not wrapped_thing['bar'][0] thing['baz'][0] is not wrapped_thing['baz'][0] thing['none'] is not wrapped_thing['none'] thing['text'] is not wrapped_thing['text']
def test_wrap_var_unsafe_bytes(): assert isinstance(wrap_var(AssibleUnsafeBytes(b'foo')), AssibleUnsafeBytes)
def test_wrap_var_None(): assert wrap_var(None) is None assert not isinstance(wrap_var(None), AssibleUnsafe)
def test_wrap_var_unsafe_text(): assert isinstance(wrap_var(AssibleUnsafeText(u'foo')), AssibleUnsafeText)
def test_wrap_var_tuple(): assert isinstance(wrap_var(('foo',)), tuple) assert not isinstance(wrap_var(('foo',)), AssibleUnsafe) assert isinstance(wrap_var(('foo',))[0], AssibleUnsafe)
def test_wrap_var_tuple_None(): assert wrap_var((None,))[0] is None assert not isinstance(wrap_var((None,))[0], AssibleUnsafe)
def _lookup(self, name, *args, **kwargs): instance = self._lookup_loader.get(name, loader=self._loader, templar=self) if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) errors = kwargs.pop('errors', 'strict') from assible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) # safely catch run failures per #5059 try: ran = instance.run(loop_terms, variables=self._available_variables, **kwargs) except (AssibleUndefinedVariable, UndefinedError) as e: raise AssibleUndefinedVariable(e) except Exception as e: if self._fail_on_lookup_errors: msg = u"An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % \ (name, type(e), to_text(e)) if errors == 'warn': display.warning(msg) elif errors == 'ignore': display.display(msg, log_only=True) else: raise AssibleError(to_native(msg)) ran = [] if wantlist else None if ran and not allow_unsafe: if wantlist: ran = wrap_var(ran) else: try: if self.jinja2_native and isinstance( ran[0], NativeJinjaText): ran = wrap_var(NativeJinjaText(",".join(ran))) else: ran = wrap_var(",".join(ran)) except TypeError: # Lookup Plugins should always return lists. Throw an error if that's not # the case: if not isinstance(ran, Sequence): raise AssibleError( "The lookup plugin '%s' did not return a list." % name) # The TypeError we can recover from is when the value *inside* of the list # is not a string if len(ran) == 1: ran = wrap_var(ran[0]) else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AssibleError("lookup plugin (%s) not found" % name)
def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, disable_lookups=False): if self.jinja2_native and not isinstance(data, string_types): return data # For preserving the number of input newlines in the output (used # later in this method) data_newlines = _count_newlines_from_end(data) if fail_on_undefined is None: fail_on_undefined = self._fail_on_undefined_errors try: # allows template header overrides to change jinja2 options. if overrides is None: myenv = self.environment.overlay() else: myenv = self.environment.overlay(overrides) # Get jinja env overrides from template if hasattr(data, 'startswith') and data.startswith(JINJA2_OVERRIDE): eol = data.find('\n') line = data[len(JINJA2_OVERRIDE):eol] data = data[eol + 1:] for pair in line.split(','): (key, val) = pair.split(':') key = key.strip() setattr(myenv, key, ast.literal_eval(val.strip())) # Adds Assible custom filters and tests myenv.filters.update(self._get_filters()) for k in myenv.filters: if not getattr(myenv.filters[k], '__UNROLLED__', False): myenv.filters[k] = _unroll_iterator(myenv.filters[k]) myenv.tests.update(self._get_tests()) if escape_backslashes: # Allow users to specify backslashes in playbooks as "\\" instead of as "\\\\". data = _escape_backslashes(data, myenv) try: t = myenv.from_string(data) except TemplateSyntaxError as e: raise AssibleError( "template error while templating string: %s. String: %s" % (to_native(e), to_native(data))) except Exception as e: if 'recursion' in to_native(e): raise AssibleError( "recursive loop detected in template string: %s" % to_native(data)) else: return data if disable_lookups: t.globals['query'] = t.globals['q'] = t.globals[ 'lookup'] = self._fail_lookup jvars = AssibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try: if self.jinja2_native: res = assible_native_concat(rf) else: res = j2_concat(rf) if getattr(new_context, 'unsafe', False): res = wrap_var(res) except TypeError as te: if 'AssibleUndefined' in to_native(te): errmsg = "Unable to look up a name or access an attribute in template string (%s).\n" % to_native( data) errmsg += "Make sure your variable name does not contain invalid characters like '-': %s" % to_native( te) raise AssibleUndefinedVariable(errmsg) else: display.debug( "failing because of a type error, template data is: %s" % to_text(data)) raise AssibleError( "Unexpected templating type error occurred on (%s): %s" % (to_native(data), to_native(te))) if self.jinja2_native and not isinstance(res, string_types): return res if preserve_trailing_newlines: # The low level calls above do not preserve the newline # characters at the end of the input data, so we use the # calculate the difference in newlines and append them # to the resulting output for parity # # jinja2 added a keep_trailing_newline option in 2.7 when # creating an Environment. That would let us make this code # better (remove a single newline if # preserve_trailing_newlines is False). Once we can depend on # that version being present, modify our code to set that when # initializing self.environment and remove a single trailing # newline here if preserve_newlines is False. res_newlines = _count_newlines_from_end(res) if data_newlines > res_newlines: res += self.environment.newline_sequence * (data_newlines - res_newlines) return res except (UndefinedError, AssibleUndefinedVariable) as e: if fail_on_undefined: raise AssibleUndefinedVariable(e) else: display.debug("Ignoring undefined failure: %s" % to_text(e)) return data
def test_wrap_var_list(): assert isinstance(wrap_var(['foo']), list) assert not isinstance(wrap_var(['foo']), AssibleUnsafe) assert isinstance(wrap_var([u'foo'])[0], AssibleUnsafeText)
def get_vars(self, play=None, host=None, task=None, include_hostvars=True, include_delegate_to=True, use_cache=True, _hosts=None, _hosts_all=None, stage='task'): ''' Returns the variables, with optional "context" given via the parameters for the play, host, and task (which could possibly result in different sets of variables being returned due to the additional context). The order of precedence is: - play->roles->get_default_vars (if there is a play context) - group_vars_files[host] (if there is a host context) - host_vars_files[host] (if there is a host context) - host->get_vars (if there is a host context) - fact_cache[host] (if there is a host context) - play vars (if there is a play context) - play vars_files (if there's no host context, ignore file names that cannot be templated) - task->get_vars (if there is a task context) - vars_cache[host] (if there is a host context) - extra vars ``_hosts`` and ``_hosts_all`` should be considered private args, with only internal trusted callers relying on the functionality they provide. These arguments may be removed at a later date without a deprecation period and without warning. ''' display.debug("in VariableManager get_vars()") all_vars = dict() magic_variables = self._get_magic_variables( play=play, host=host, task=task, include_hostvars=include_hostvars, include_delegate_to=include_delegate_to, _hosts=_hosts, _hosts_all=_hosts_all, ) _vars_sources = {} def _combine_and_track(data, new_data, source): ''' Wrapper function to update var sources dict and call combine_vars() See notes in the VarsWithSources docstring for caveats and limitations of the source tracking ''' if C.DEFAULT_DEBUG: # Populate var sources dict for key in new_data: _vars_sources[key] = source return combine_vars(data, new_data) # default for all cases basedirs = [] if self.safe_basedir: # avoid adhoc/console loading cwd basedirs = [self._loader.get_basedir()] if play: # first we compile any vars specified in defaults/main.yml # for all roles within the specified play for role in play.get_roles(): all_vars = _combine_and_track(all_vars, role.get_default_vars(), "role '%s' defaults" % role.name) if task: # set basedirs if C.PLAYBOOK_VARS_ROOT == 'all': # should be default basedirs = task.get_search_path() elif C.PLAYBOOK_VARS_ROOT in ( 'bottom', 'playbook_dir'): # only option in 2.4.0 basedirs = [task.get_search_path()[0]] elif C.PLAYBOOK_VARS_ROOT != 'top': # preserves default basedirs, only option pre 2.3 raise AssibleError('Unknown playbook vars logic: %s' % C.PLAYBOOK_VARS_ROOT) # if we have a task in this context, and that task has a role, make # sure it sees its defaults above any other roles, as we previously # (v1) made sure each task had a copy of its roles default vars if task._role is not None and (play or task.action == 'include_role'): all_vars = _combine_and_track( all_vars, task._role.get_default_vars( dep_chain=task.get_dep_chain()), "role '%s' defaults" % task._role.name) if host: # THE 'all' group and the rest of groups for a host, used below all_group = self._inventory.groups.get('all') host_groups = sort_groups( [g for g in host.get_groups() if g.name not in ['all']]) def _get_plugin_vars(plugin, path, entities): data = {} try: data = plugin.get_vars(self._loader, path, entities) except AttributeError: try: for entity in entities: if isinstance(entity, Host): data.update(plugin.get_host_vars(entity.name)) else: data.update(plugin.get_group_vars(entity.name)) except AttributeError: if hasattr(plugin, 'run'): raise AssibleError( "Cannot use v1 type vars plugin %s from %s" % (plugin._load_name, plugin._original_path)) else: raise AssibleError( "Invalid vars plugin %s from %s" % (plugin._load_name, plugin._original_path)) return data # internal functions that actually do the work def _plugins_inventory(entities): ''' merges all entities by inventory source ''' return get_vars_from_inventory_sources( self._loader, self._inventory._sources, entities, stage) def _plugins_play(entities): ''' merges all entities adjacent to play ''' data = {} for path in basedirs: data = _combine_and_track( data, get_vars_from_path(self._loader, path, entities, stage), "path '%s'" % path) return data # configurable functions that are sortable via config, remember to add to _ALLOWED if expanding this list def all_inventory(): return all_group.get_vars() def all_plugins_inventory(): return _plugins_inventory([all_group]) def all_plugins_play(): return _plugins_play([all_group]) def groups_inventory(): ''' gets group vars from inventory ''' return get_group_vars(host_groups) def groups_plugins_inventory(): ''' gets plugin sources from inventory for groups ''' return _plugins_inventory(host_groups) def groups_plugins_play(): ''' gets plugin sources from play for groups ''' return _plugins_play(host_groups) def plugins_by_groups(): ''' merges all plugin sources by group, This should be used instead, NOT in combination with the other groups_plugins* functions ''' data = {} for group in host_groups: data[group] = _combine_and_track( data[group], _plugins_inventory(group), "inventory group_vars for '%s'" % group) data[group] = _combine_and_track( data[group], _plugins_play(group), "playbook group_vars for '%s'" % group) return data # Merge groups as per precedence config # only allow to call the functions we want exposed for entry in C.VARIABLE_PRECEDENCE: if entry in self._ALLOWED: display.debug('Calling %s to load vars for %s' % (entry, host.name)) all_vars = _combine_and_track( all_vars, locals()[entry](), "group vars, precedence entry '%s'" % entry) else: display.warning( 'Ignoring unknown variable precedence entry: %s' % (entry)) # host vars, from inventory, inventory adjacent and play adjacent via plugins all_vars = _combine_and_track(all_vars, host.get_vars(), "host vars for '%s'" % host) all_vars = _combine_and_track( all_vars, _plugins_inventory([host]), "inventory host_vars for '%s'" % host) all_vars = _combine_and_track(all_vars, _plugins_play([host]), "playbook host_vars for '%s'" % host) # finally, the facts caches for this host, if it exists # TODO: cleaning of facts should eventually become part of taskresults instead of vars try: facts = wrap_var(self._fact_cache.get(host.name, {})) all_vars.update(namespace_facts(facts)) # push facts to main namespace if C.INJECT_FACTS_AS_VARS: all_vars = _combine_and_track(all_vars, wrap_var(clean_facts(facts)), "facts") else: # always 'promote' assible_local all_vars = _combine_and_track( all_vars, wrap_var( {'assible_local': facts.get('assible_local', {})}), "facts") except KeyError: pass if play: all_vars = _combine_and_track(all_vars, play.get_vars(), "play vars") vars_files = play.get_vars_files() try: for vars_file_item in vars_files: # create a set of temporary vars here, which incorporate the extra # and magic vars so we can properly template the vars_files entries temp_vars = combine_vars(all_vars, self._extra_vars) temp_vars = combine_vars(temp_vars, magic_variables) templar = Templar(loader=self._loader, variables=temp_vars) # we assume each item in the list is itself a list, as we # support "conditional includes" for vars_files, which mimics # the with_first_found mechanism. vars_file_list = vars_file_item if not isinstance(vars_file_list, list): vars_file_list = [vars_file_list] # now we iterate through the (potential) files, and break out # as soon as we read one from the list. If none are found, we # raise an error, which is silently ignored at this point. try: for vars_file in vars_file_list: vars_file = templar.template(vars_file) if not (isinstance(vars_file, Sequence)): raise AssibleError( "Invalid vars_files entry found: %r\n" "vars_files entries should be either a string type or " "a list of string types after template expansion" % vars_file) try: data = preprocess_vars( self._loader.load_from_file(vars_file, unsafe=True)) if data is not None: for item in data: all_vars = _combine_and_track( all_vars, item, "play vars_files from '%s'" % vars_file) break except AssibleFileNotFound: # we continue on loader failures continue except AssibleParserError: raise else: # if include_delegate_to is set to False, we ignore the missing # vars file here because we're working on a delegated host if include_delegate_to: raise AssibleFileNotFound( "vars file %s was not found" % vars_file_item) except (UndefinedError, AssibleUndefinedVariable): if host is not None and self._fact_cache.get( host.name, dict()).get( 'module_setup') and task is not None: raise AssibleUndefinedVariable( "an undefined variable was found when attempting to template the vars_files item '%s'" % vars_file_item, obj=vars_file_item) else: # we do not have a full context here, and the missing variable could be because of that # so just show a warning and continue display.vvv( "skipping vars_file '%s' due to an undefined variable" % vars_file_item) continue display.vvv("Read vars_file '%s'" % vars_file_item) except TypeError: raise AssibleParserError( "Error while reading vars files - please supply a list of file names. " "Got '%s' of type %s" % (vars_files, type(vars_files))) # By default, we now merge in all vars from all roles in the play, # unless the user has disabled this via a config option if not C.DEFAULT_PRIVATE_ROLE_VARS: for role in play.get_roles(): all_vars = _combine_and_track( all_vars, role.get_vars(include_params=False), "role '%s' vars" % role.name) # next, we merge in the vars from the role, which will specifically # follow the role dependency chain, and then we merge in the tasks # vars (which will look at parent blocks/task includes) if task: if task._role: all_vars = _combine_and_track( all_vars, task._role.get_vars(task.get_dep_chain(), include_params=False), "role '%s' vars" % task._role.name) all_vars = _combine_and_track(all_vars, task.get_vars(), "task vars") # next, we merge in the vars cache (include vars) and nonpersistent # facts cache (set_fact/register), in that order if host: # include_vars non-persistent cache all_vars = _combine_and_track( all_vars, self._vars_cache.get(host.get_name(), dict()), "include_vars") # fact non-persistent cache all_vars = _combine_and_track( all_vars, self._nonpersistent_fact_cache.get(host.name, dict()), "set_fact") # next, we merge in role params and task include params if task: if task._role: all_vars = _combine_and_track( all_vars, task._role.get_role_params(task.get_dep_chain()), "role '%s' params" % task._role.name) # special case for include tasks, where the include params # may be specified in the vars field for the task, which should # have higher precedence than the vars/np facts above all_vars = _combine_and_track(all_vars, task.get_include_params(), "include params") # extra vars all_vars = _combine_and_track(all_vars, self._extra_vars, "extra vars") # magic variables all_vars = _combine_and_track(all_vars, magic_variables, "magic vars") # special case for the 'environment' magic variable, as someone # may have set it as a variable and we don't want to stomp on it if task: all_vars['environment'] = task.environment # 'vars' magic var if task or play: # has to be copy, otherwise recursive ref all_vars['vars'] = all_vars.copy() # if we have a task and we're delegating to another host, figure out the # variables for that host now so we don't have to rely on hostvars later if task and task.delegate_to is not None and include_delegate_to: all_vars['assible_delegated_vars'], all_vars[ '_assible_loop_cache'] = self._get_delegated_vars( play, task, all_vars) display.debug("done with get_vars()") if C.DEFAULT_DEBUG: # Use VarsWithSources wrapper class to display var sources return VarsWithSources.new_vars_with_sources( all_vars, _vars_sources) else: return all_vars
def test_wrap_var_dict_None(): assert wrap_var(dict(foo=None))['foo'] is None assert not isinstance(wrap_var(dict(foo=None))['foo'], AssibleUnsafe)
def test_wrap_var_dict(): assert isinstance(wrap_var(dict(foo='bar')), dict) assert not isinstance(wrap_var(dict(foo='bar')), AssibleUnsafe) assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AssibleUnsafeText)
def test_wrap_var_string(): if PY3: assert isinstance(wrap_var('foo'), AssibleUnsafeText) else: assert isinstance(wrap_var('foo'), AssibleUnsafeBytes)
def construct_yaml_unsafe(self, node): return wrap_var(self.construct_yaml_str(node))
def test_wrap_var_set_None(): for item in wrap_var(set([None])): assert item is None assert not isinstance(item, AssibleUnsafe)
def test_wrap_var_list_None(): assert wrap_var([None])[0] is None assert not isinstance(wrap_var([None])[0], AssibleUnsafe)
def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, convert_data=True, static_vars=None, cache=True, disable_lookups=False): ''' Templates (possibly recursively) any given data as input. If convert_bare is set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}') before being sent through the template engine. ''' static_vars = [''] if static_vars is None else static_vars # Don't template unsafe variables, just return them. if hasattr(variable, '__UNSAFE__'): return variable if fail_on_undefined is None: fail_on_undefined = self._fail_on_undefined_errors try: if convert_bare: variable = self._convert_bare_variable(variable) if isinstance(variable, string_types): result = variable if self.is_possibly_template(variable): # Check to see if the string we are trying to render is just referencing a single # var. In this case we don't want to accidentally change the type of the variable # to a string by using the jinja template renderer. We just want to pass it. only_one = self.SINGLE_VAR.match(variable) if only_one: var_name = only_one.group(1) if var_name in self._available_variables: resolved_val = self._available_variables[var_name] if isinstance(resolved_val, NON_TEMPLATED_TYPES): return resolved_val elif resolved_val is None: return C.DEFAULT_NULL_REPRESENTATION # Using a cache in order to prevent template calls with already templated variables sha1_hash = None if cache: variable_hash = sha1( text_type(variable).encode('utf-8')) options_hash = sha1( (text_type(preserve_trailing_newlines) + text_type(escape_backslashes) + text_type(fail_on_undefined) + text_type(overrides)).encode('utf-8')) sha1_hash = variable_hash.hexdigest( ) + options_hash.hexdigest() if cache and sha1_hash in self._cached_result: result = self._cached_result[sha1_hash] else: result = self.do_template( variable, preserve_trailing_newlines= preserve_trailing_newlines, escape_backslashes=escape_backslashes, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) if not self.jinja2_native: unsafe = hasattr(result, '__UNSAFE__') if convert_data and not self._no_type_regex.match( variable): # if this looks like a dictionary or list, convert it to such using the safe_eval method if (result.startswith("{") and not result.startswith(self.environment.variable_start_string)) or \ result.startswith("[") or result in ("True", "False"): eval_results = safe_eval( result, include_exceptions=True) if eval_results[1] is None: result = eval_results[0] if unsafe: result = wrap_var(result) else: # FIXME: if the safe_eval raised an error, should we do something with it? pass # we only cache in the case where we have a single variable # name, to make sure we're not putting things which may otherwise # be dynamic in the cache (filters, lookups, etc.) if cache and only_one: self._cached_result[sha1_hash] = result return result elif is_sequence(variable): return [ self.template( v, preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) for v in variable ] elif isinstance(variable, Mapping): d = {} # we don't use iteritems() here to avoid problems if the underlying dict # changes sizes due to the templating, which can happen with hostvars for k in variable.keys(): if k not in static_vars: d[k] = self.template( variable[k], preserve_trailing_newlines= preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides, disable_lookups=disable_lookups, ) else: d[k] = variable[k] return d else: return variable except AssibleFilterError: if self._fail_on_filter_errors: raise else: return variable
def _get_delegated_vars(self, play, task, existing_variables): # This method has a lot of code copied from ``TaskExecutor._get_loop_items`` # if this is failing, and ``TaskExecutor._get_loop_items`` is not # then more will have to be copied here. # TODO: dedupe code here and with ``TaskExecutor._get_loop_items`` # this may be possible once we move pre-processing pre fork if not hasattr(task, 'loop'): # This "task" is not a Task, so we need to skip it return {}, None # we unfortunately need to template the delegate_to field here, # as we're fetching vars before post_validate has been called on # the task that has been passed in vars_copy = existing_variables.copy() # get search path for this task to pass to lookup plugins vars_copy['assible_search_path'] = task.get_search_path() # ensure basedir is always in (dwim already searches here but we need to display it) if self._loader.get_basedir() not in vars_copy['assible_search_path']: vars_copy['assible_search_path'].append(self._loader.get_basedir()) templar = Templar(loader=self._loader, variables=vars_copy) items = [] has_loop = True if task.loop_with is not None: if task.loop_with in lookup_loader: fail = True if task.loop_with == 'first_found': # first_found loops are special. If the item is undefined then we want to fall through to the next fail = False try: loop_terms = listify_lookup_plugin_terms( terms=task.loop, templar=templar, loader=self._loader, fail_on_undefined=fail, convert_bare=False) if not fail: loop_terms = [ t for t in loop_terms if not templar.is_template(t) ] mylookup = lookup_loader.get(task.loop_with, loader=self._loader, templar=templar) # give lookup task 'context' for subdir (mostly needed for first_found) for subdir in ['template', 'var', 'file']: # TODO: move this to constants? if subdir in task.action: break setattr(mylookup, '_subdir', subdir + 's') items = wrap_var( mylookup.run(terms=loop_terms, variables=vars_copy)) except AssibleTemplateError: # This task will be skipped later due to this, so we just setup # a dummy array for the later code so it doesn't fail items = [None] else: raise AssibleError( "Failed to find the lookup named '%s' in the available lookup plugins" % task.loop_with) elif task.loop is not None: try: items = templar.template(task.loop) except AssibleTemplateError: # This task will be skipped later due to this, so we just setup # a dummy array for the later code so it doesn't fail items = [None] else: has_loop = False items = [None] # since host can change per loop, we keep dict per host name resolved delegated_host_vars = dict() item_var = getattr(task.loop_control, 'loop_var', 'item') cache_items = False for item in items: # update the variables with the item value for templating, in case we need it if item is not None: vars_copy[item_var] = item templar.available_variables = vars_copy delegated_host_name = templar.template(task.delegate_to, fail_on_undefined=False) if delegated_host_name != task.delegate_to: cache_items = True if delegated_host_name is None: raise AssibleError( message="Undefined delegate_to host for task:", obj=task._ds) if not isinstance(delegated_host_name, string_types): raise AssibleError( message= "the field 'delegate_to' has an invalid type (%s), and could not be" " converted to a string type." % type(delegated_host_name), obj=task._ds) if delegated_host_name in delegated_host_vars: # no need to repeat ourselves, as the delegate_to value # does not appear to be tied to the loop item variable continue # now try to find the delegated-to host in inventory, or failing that, # create a new host on the fly so we can fetch variables for it delegated_host = None if self._inventory is not None: delegated_host = self._inventory.get_host(delegated_host_name) # try looking it up based on the address field, and finally # fall back to creating a host on the fly to use for the var lookup if delegated_host is None: for h in self._inventory.get_hosts( ignore_limits=True, ignore_restrictions=True): # check if the address matches, or if both the delegated_to host # and the current host are in the list of localhost aliases if h.address == delegated_host_name: delegated_host = h break else: delegated_host = Host(name=delegated_host_name) else: delegated_host = Host(name=delegated_host_name) # now we go fetch the vars for the delegated-to host and save them in our # master dictionary of variables to be used later in the TaskExecutor/PlayContext delegated_host_vars[delegated_host_name] = self.get_vars( play=play, host=delegated_host, task=task, include_delegate_to=False, include_hostvars=True, ) delegated_host_vars[delegated_host_name][ 'inventory_hostname'] = vars_copy.get('inventory_hostname') _assible_loop_cache = None if has_loop and cache_items: # delegate_to templating produced a change, so we will cache the templated items # in a special private hostvar # this ensures that delegate_to+loop doesn't produce different results than TaskExecutor # which may reprocess the loop _assible_loop_cache = items return delegated_host_vars, _assible_loop_cache
def test_wrap_var_set(): assert isinstance(wrap_var(set(['foo'])), set) assert not isinstance(wrap_var(set(['foo'])), AssibleUnsafe) for item in wrap_var(set([u'foo'])): assert isinstance(item, AssibleUnsafeText)