.. versionadded:: 2015.5.0

    List the available LXC template scripts installed on the minion

    CLI Examples:

    .. code-block:: bash

        salt myminion lxc.templates
973130
def templates():
    '''
    
    '''
    try:
        template_scripts = os.listdir('/usr/share/lxc/templates')
    except OSError:
        return []
    else:
        return [x[4:] for x in template_scripts if x.startswith('lxc-')]
45360
def installed_template_manifest_patterns

    # 1) search .    # that is, working/current dir
    # 2) search <config_dir>
    # 3) search <gem>/templates

###
# Note
# -- for now - no longer ship w/ builtin template packs
# - download on demand if needed

    builtin_patterns = [
##      "#{Pluto.root}/templates/*.txt"
    ]
    config_patterns  = [
##      "#{File.expand_path(opts.config_path)}/*.txt",
      "#{File.expand_path(opts.config_path)}/*/*.txt"
    ]
    current_patterns = [
##      "*.txt",
      "*/*.txt",
      "node_modules/*/*.txt", # note: add support for npm installs - use/make slideshow required in name? for namespace in the future???
    ]

    patterns = []
    patterns += current_patterns
    patterns += config_patterns
    patterns += builtin_patterns
  end
203679
def create_lxc(name, template='ubuntu', service=None):
    """"""
    service = service or LXCService
    service.create(name, template=template)
    meta = LXCMeta(initial=dict(type='LXC'))
    lxc = LXC.with_meta(name, service, meta, save=True)
    return lxc
1252642
def list_extmods():
    '''
    
    '''
    ret = {}
    ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
    mod_types = os.listdir(ext_dir)
    for mod_type in mod_types:
        ret[mod_type] = set()
        for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
            for fh_ in files:
                ret[mod_type].add(fh_.split('.')[0])
        ret[mod_type] = list(ret[mod_type])
    return ret
281404
function jsdocCommand( jsdoc ) {
	var cmd = [];
	cmd.unshift( jsdoc.options );
	if ( jsdoc.tutorials.length > 0 ) {
		cmd.push( "-u " + path.resolve( jsdoc.tutorials ) );
	}
	cmd.push( "-d " + path.resolve( jsdoc.dest ) );
	cmd.push( "-t " + path.resolve( jsdoc.template ) );
	cmd.push( "-c " + path.resolve( jsdoc.config ) );
	sys.each( jsdoc.src, function ( src ) {
		cmd.push( path.resolve( src ) );
	} );
	cmd.unshift( path.resolve( "./node_modules/jsdoc/jsdoc" ) );
	cmd.unshift( "node" );

	return cmd.join( " " );
}
84106
def ext_pillar(minion_id,  # pylint: disable=W0613
               pillar,  # pylint: disable=W0613
               config_file):
    '''
    
    '''
    config_template = None
    try:
        config_template = _render_template(config_file)
    except jinja2.exceptions.TemplateNotFound:
        log.debug('pillar_ldap: missing configuration file %s', config_file)
    except Exception:
        log.debug('pillar_ldap: failed to render template for %s',
                  config_file, exc_info=True)

    if not config_template:
        # We don't have a config file
        return {}

    import salt.utils.yaml
    try:
        opts = salt.utils.yaml.safe_load(config_template) or {}
        opts['conf_file'] = config_file
    except Exception as err:
        import salt.log
        msg = 'pillar_ldap: error parsing configuration file: {0} - {1}'.format(
            config_file, err
        )
        if salt.log.is_console_configured():
            log.warning(msg)
        else:
            print(msg)
        return {}
    else:
        if not isinstance(opts, dict):
            log.warning(
                'pillar_ldap: %s is invalidly formatted, must be a YAML '
                'dictionary. See the documentation for more information.',
                config_file
            )
            return {}

    if 'search_order' not in opts:
        log.warning(
            'pillar_ldap: search_order missing from configuration. See the '
            'documentation for more information.'
        )
        return {}

    data = {}
    for source in opts['search_order']:
        config = opts[source]
        result = _do_search(config)
        log.debug('source %s got result %s', source, result)
        if result:
            data = _result_to_dict(data, result, config, source)
    return data
1084073
def template(ctx, url, no_input, role_name):  # pragma: no cover
    
    command_args = {
        'role_name': role_name,
        'subcommand': __name__,
        'url': url,
        'no_input': no_input,
    }

    t = Template(command_args)
    t.execute()
1194576
def search_lxc_bridges():
    '''
    

    '''
    bridges = __context__.get('lxc.bridges', None)
    # either match not yet called or no bridges were found
    # to handle the case where lxc was not installed on the first
    # call
    if not bridges:
        bridges = set()
        running_bridges = set()
        bridges.add(DEFAULT_BR)
        try:
            output = __salt__['cmd.run_all']('brctl show')
            for line in output['stdout'].splitlines()[1:]:
                if not line.startswith(' '):
                    running_bridges.add(line.split()[0].strip())
        except (SaltInvocationError, CommandExecutionError):
            pass
        for ifc, ip in six.iteritems(
            __grains__.get('ip_interfaces', {})
        ):
            if ifc in running_bridges:
                bridges.add(ifc)
            elif os.path.exists(
                '/sys/devices/virtual/net/{0}/bridge'.format(ifc)
            ):
                bridges.add(ifc)
        bridges = list(bridges)
        # if we found interfaces that have lxc in their names
        # we filter them as being the potential lxc bridges
        # we also try to default on br0 on other cases

        def sort_bridges(a):
            pref = 'z'
            if 'lxc' in a:
                pref = 'a'
            elif 'br0' == a:
                pref = 'c'
            return '{0}_{1}'.format(pref, a)
        bridges.sort(key=sort_bridges)
        __context__['lxc.bridges'] = bridges
    return bridges
1138839
def compile_template_str(template, renderers, default, blacklist, whitelist):
    '''
    
    '''
    fn_ = salt.utils.files.mkstemp()
    with salt.utils.files.fopen(fn_, 'wb') as ofile:
        ofile.write(SLS_ENCODER(template)[0])
    return compile_template(fn_, renderers, default, blacklist, whitelist)
992611
def versions():
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        minions = client.cmd('*', 'test.version', timeout=__opts__['timeout'])
    except SaltClientError as client_error:
        print(client_error)
        return ret

    labels = {
        -2: 'Minion offline',
        -1: 'Minion requires update',
        0: 'Up to date',
        1: 'Minion newer than master',
        2: 'Master',
    }

    version_status = {}

    master_version = salt.version.__saltstack_version__

    for minion in minions:
        if not minions[minion]:
            minion_version = False
            ver_diff = -2
        else:
            minion_version = salt.version.SaltStackVersion.parse(minions[minion])
            ver_diff = salt.utils.compat.cmp(minion_version, master_version)

        if ver_diff not in version_status:
            version_status[ver_diff] = {}
        if minion_version:
            version_status[ver_diff][minion] = minion_version.string
        else:
            version_status[ver_diff][minion] = minion_version

    # Add version of Master to output
    version_status[2] = master_version.string

    for key in version_status:
        if key == 2:
            ret[labels[key]] = version_status[2]
        else:
            for minion in sorted(version_status[key]):
                ret.setdefault(labels[key], {})[minion] = version_status[key][minion]
    return ret
800270
def __read_and_render_yaml_file(source,
                                template,
                                saltenv):
    '''
    
    '''
    sfn = __salt__['cp.cache_file'](source, saltenv)
    if not sfn:
        raise CommandExecutionError(
            'Source file \'{0}\' not found'.format(source))

    with salt.utils.files.fopen(sfn, 'r') as src:
        contents = src.read()

        if template:
            if template in salt.utils.templates.TEMPLATE_REGISTRY:
                # TODO: should we allow user to set also `context` like  # pylint: disable=fixme
                # `file.managed` does?
                # Apply templating
                data = salt.utils.templates.TEMPLATE_REGISTRY[template](
                    contents,
                    from_str=True,
                    to_str=True,
                    saltenv=saltenv,
                    grains=__grains__,
                    pillar=__pillar__,
                    salt=__salt__,
                    opts=__opts__)

                if not data['result']:
                    # Failed to render the template
                    raise CommandExecutionError(
                        'Failed to render file path with error: '
                        '{0}'.format(data['data'])
                    )

                contents = data['data'].encode('utf-8')
            else:
                raise CommandExecutionError(
                    'Unknown template specified: {0}'.format(
                        template))

        return salt.utils.yaml.safe_load(contents)
799590
function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }
965055
def ensure_container(self, name=None):
        """"""
        if get_lxc_version() < pkg_resources.parse_version('2.0.0'):
            # Nothing to do for old versions of LXC
            return

        if name is None:
            name = self.container_name

        args = [
            'lxc-create',
            '--name', name,
            '--template', 'none',
            '>', '/dev/null', '2>&1',
        ]
        os.system(' '.join(args))
725162
def command_template(self):
        
        com_out = self.appname
        for key, val in self.args.items():
            if key in self._options:
                com_out += ' %s={%s}' % (key, key)
            else:
                com_out += ' %s=%s' % (key, val)
        return com_out
921718
def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0):
    ''''''
    if suffix==None:
        suffix = '_sstemplate'
    if prefix==None:
        prefix = nl.suffix(dset,suffix)
    if not os.path.exists(prefix):
        with nl.notify('Running template-based skull-strip on %s' % dset):
            dset = os.path.abspath(dset)
            template = os.path.abspath(template)
            tmp_dir = tempfile.mkdtemp()
            cwd = os.getcwd()
            with nl.run_in(tmp_dir):
                nl.affine_align(template,dset,skull_strip=None,cost='mi',opts=['-nmatch','100%'])
                nl.run(['3dQwarp','-minpatch','20','-penfac','10','-noweight','-source',nl.suffix(template,'_aff'),'-base',dset,'-prefix',nl.suffix(template,'_qwarp')],products=nl.suffix(template,'_qwarp'))
                info = nl.dset_info(nl.suffix(template,'_qwarp'))
                max_value = info.subbricks[0]['max']
                nl.calc([dset,nl.suffix(template,'_qwarp')],'a*step(b-%f*0.05)'%max_value,prefix)
                shutil.move(prefix,cwd)
            shutil.rmtree(tmp_dir)
544902
def _get_template_texts(source_list=None,
                        template='jinja',
                        defaults=None,
                        context=None,
                        **kwargs):
    '''
    
    '''

    ret = {'name': '_get_template_texts',
           'changes': {},
           'result': True,
           'comment': '',
           'data': []}

    if source_list is None:
        return _error(ret,
                      '_get_template_texts called with empty source_list')

    txtl = []

    for (source, source_hash) in source_list:

        context_dict = defaults if defaults else {}
        if context:
            context_dict = salt.utils.dictupdate.merge(context_dict, context)
        rndrd_templ_fn = __salt__['cp.get_template'](
            source,
            '',
            template=template,
            saltenv=__env__,
            context=context_dict,
            **kwargs
        )
        log.debug('cp.get_template returned %s (Called with: %s)',
                  rndrd_templ_fn, source)
        if rndrd_templ_fn:
            tmplines = None
            with salt.utils.files.fopen(rndrd_templ_fn, 'rb') as fp_:
                tmplines = fp_.read()
                tmplines = salt.utils.stringutils.to_unicode(tmplines)
                tmplines = tmplines.splitlines(True)
            if not tmplines:
                msg = 'Failed to read rendered template file {0} ({1})'.format(
                    rndrd_templ_fn, source
                )
                log.debug(msg)
                ret['name'] = source
                return _error(ret, msg)
            txtl.append(''.join(tmplines))
        else:
            msg = 'Failed to load template file {0}'.format(source)
            log.debug(msg)
            ret['name'] = source
            return _error(ret, msg)

    ret['data'] = txtl
    return ret
123928
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
    '''
    
    '''
    if not template:
        return (cmd, cwd)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    if pillarenv is not None or pillar_override is not None:
        pillarenv = pillarenv or __opts__['pillarenv']
        kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override)
    else:
        kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to execute cmd with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    cmd = _render(cmd)
    cwd = _render(cwd)
    return (cmd, cwd)