Ejemplo n.º 1
0
def _jinja(sfn, name, source, user, group, mode, env, context=None):
    '''
    Render a jinja2 template, returns the location of the rendered file,
    return False if render fails.
    Returns::

        {'result': bool,
         'data': <Error data or rendered file path>}
    '''
    try:
        from salt.utils.jinja import get_template
    except ImportError:
        return {'result': False,
                'data': 'Failed to import jinja'}
    try:
        tgt = tempfile.mkstemp()[1]
        passthrough = context if context else {}
        passthrough['salt'] = __salt__
        passthrough['grains'] = __grains__
        passthrough['name'] = name
        passthrough['source'] = source
        passthrough['user'] = user
        passthrough['group'] = group
        passthrough['mode'] = mode
        passthrough['env'] = env
        template = get_template(sfn, __opts__, env)
        open(tgt, 'w+').write(template.render(**passthrough))
        return {'result': True,
                    'data': tgt}
    except:
        trb = traceback.format_exc()
        return {'result': False,
                'data': trb}
Ejemplo n.º 2
0
Archivo: file.py Proyecto: vittyvk/salt
def _jinja(sfn, name, source, user, group, mode, env, context=None):
    """
    Render a jinja2 template, returns the location of the rendered file,
    return False if render fails.
    Returns::

        {'result': bool,
         'data': <Error data or rendered file path>}
    """
    try:
        from salt.utils.jinja import get_template
    except ImportError:
        return {"result": False, "data": "Failed to import jinja"}
    try:
        tgt = tempfile.mkstemp()[1]
        passthrough = context if context else {}
        passthrough["salt"] = __salt__
        passthrough["grains"] = __grains__
        passthrough["name"] = name
        passthrough["source"] = source
        passthrough["user"] = user
        passthrough["group"] = group
        passthrough["mode"] = mode
        passthrough["env"] = env
        template = get_template(sfn, __opts__, env)
        open(tgt, "w+").write(template.render(**passthrough))
        return {"result": True, "data": tgt}
    except:
        trb = traceback.format_exc()
        return {"result": False, "data": trb}
Ejemplo n.º 3
0
 def test_fallback_noloader(self):
     '''
     If the fallback is used any attempt to load other templates
     will raise a TypeError.
     '''
     filename = '%s/files/test/hello_import' % TEMPLATES_DIR
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other')
     self.assertRaises(TypeError, tmpl.render)
Ejemplo n.º 4
0
 def test_fallback(self):
     '''
     A Template without loader is returned as fallback 
     if the file is not contained in the searchpath
     '''
     filename = '%s/files/test/hello_simple' % TEMPLATES_DIR
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other')
     self.assertEqual(tmpl.render(), 'world')
Ejemplo n.º 5
0
 def test_fallback(self):
     """
     A Template with a filesystem loader is returned as fallback
     if the file is not contained in the searchpath
     """
     filename = os.path.join(TEMPLATES_DIR, "files", "test", "hello_simple")
     tmpl = get_template(filename, {"cachedir": TEMPLATES_DIR}, env="other")
     self.assertEqual(tmpl.render(), "world")
Ejemplo n.º 6
0
 def test_fallback_noloader(self):
     '''
     If the fallback is used any attempt to load other templates
     will raise a TypeError.
     '''
     filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import')
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other')
     self.assertRaises(TypeError, tmpl.render)
Ejemplo n.º 7
0
 def test_fallback_noloader(self):
     '''
     If the fallback is used any attempt to load other templates
     will raise a TypeError.
     '''
     filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import')
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other')
     self.assertRaises(TypeError, tmpl.render)
Ejemplo n.º 8
0
 def test_fallback(self):
     '''
     A Template with a filesystem loader is returned as fallback
     if the file is not contained in the searchpath
     '''
     filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_simple')
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other')
     self.assertEqual(tmpl.render(), 'world')
Ejemplo n.º 9
0
def jinja(sfn, string=False, **kwargs):
    '''
    Render a jinja2 template, returns the location of the rendered file,
    return False if render fails.
    Returns::

        {'result': bool,
         'data': <Error data or rendered file path>}
    '''
    try:
        from salt.utils.jinja import get_template
        from jinja2.exceptions import TemplateSyntaxError
    except ImportError:
        return {'result': False,
                'data': 'Failed to import jinja'}
    try:
        passthrough = {}
        newline = False
        with open(sfn, 'rb') as source:
            if source.read().endswith('\n'):
                newline = True
        fd_, tgt = tempfile.mkstemp()
        os.close(fd_)
        if 'context' in kwargs:
            passthrough = (
                kwargs['context']
                if isinstance(kwargs['context'], dict)
                else {}
            )
        for kwarg in kwargs:
            if kwarg == 'context':
                continue
            passthrough[kwarg] = kwargs[kwarg]
        template = get_template(sfn, kwargs['opts'], kwargs['env'])
        try:
            data = template.render(**passthrough)
            if string:
                salt.utils.safe_rm(tgt)
                return {'result': True,
                        'data': data}
            with open(tgt, 'w+') as target:
                target.write(data)
                if newline:
                    target.write('\n')
        except UnicodeEncodeError:
            with codecs.open(tgt, encoding='utf-8', mode='w+') as target:
                target.write(template.render(**passthrough))
                if newline:
                    target.write('\n')
        return {'result': True,
                    'data': tgt}
    except TemplateSyntaxError as exc:
        return {'result': False,
                'data': str(exc)}
    except Exception:
        trb = traceback.format_exc()
        return {'result': False,
                'data': trb}
Ejemplo n.º 10
0
def jinja(sfn, string=False, **kwargs):
    '''
    Render a jinja2 template, returns the location of the rendered file,
    return False if render fails.
    Returns::

        {'result': bool,
         'data': <Error data or rendered file path>}
    '''
    try:
        from salt.utils.jinja import get_template
        from jinja2.exceptions import TemplateSyntaxError
    except ImportError:
        return {'result': False, 'data': 'Failed to import jinja'}
    try:
        passthrough = {}
        newline = False
        with open(sfn, 'rb') as source:
            if source.read().endswith('\n'):
                newline = True
        fd_, tgt = tempfile.mkstemp()
        os.close(fd_)
        if 'context' in kwargs:
            passthrough = (kwargs['context'] if isinstance(
                kwargs['context'], dict) else {})
        for kwarg in kwargs:
            if kwarg == 'context':
                continue
            passthrough[kwarg] = kwargs[kwarg]
        template = get_template(sfn, kwargs['opts'], kwargs['env'])
        try:
            data = template.render(**passthrough)
            if string:
                salt.utils.safe_rm(tgt)
                return {'result': True, 'data': data}
            with open(tgt, 'w+') as target:
                target.write(data)
                if newline:
                    target.write('\n')
        except UnicodeEncodeError:
            with codecs.open(tgt, encoding='utf-8', mode='w+') as target:
                target.write(template.render(**passthrough))
                if newline:
                    target.write('\n')
        return {'result': True, 'data': tgt}
    except TemplateSyntaxError as exc:
        return {'result': False, 'data': str(exc)}
    except Exception:
        trb = traceback.format_exc()
        return {'result': False, 'data': trb}
Ejemplo n.º 11
0
 def test_env(self):
     '''
     If the template is within the searchpath it can
     import, include and extend other templates.
     The initial template is expected to be already cached
     get_template does not request it from the master again.
     '''
     fc = MockFileClient()
     # monkey patch file client
     _fc = SaltCacheLoader.file_client
     SaltCacheLoader.file_client = lambda loader: fc 
     filename = '%s/files/test/hello_import' % TEMPLATES_DIR
     tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='test')
     self.assertEqual(tmpl.render(a='Hi', b='Salt'), 'Hey world !Hi Salt !')
     self.assertEqual(fc.requests[0]['path'], 'salt://macro')
     SaltCacheLoader.file_client = _fc
Ejemplo n.º 12
0
 def test_env(self):
     """
     If the template is within the searchpath it can
     import, include and extend other templates.
     The initial template is expected to be already cached
     get_template does not request it from the master again.
     """
     fc = MockFileClient()
     # monkey patch file client
     _fc = SaltCacheLoader.file_client
     SaltCacheLoader.file_client = lambda loader: fc
     filename = os.path.join(TEMPLATES_DIR, "files", "test", "hello_import")
     tmpl = get_template(filename, {"cachedir": TEMPLATES_DIR}, env="test")
     self.assertEqual(tmpl.render(a="Hi", b="Salt"), "Hey world !Hi Salt !")
     self.assertEqual(fc.requests[0]["path"], "salt://macro")
     SaltCacheLoader.file_client = _fc
Ejemplo n.º 13
0
Archivo: file.py Proyecto: cmek/salt
def _jinja(sfn, name, source, user, group, mode, env, context=None):
    '''
    Render a jinja2 template, returns the location of the rendered file,
    return False if render fails.
    Returns::

        {'result': bool,
         'data': <Error data or rendered file path>}
    '''
    try:
        from salt.utils.jinja import get_template
    except ImportError:
        return {'result': False,
                'data': 'Failed to import jinja'}
    try:
        newline = False
        with open(sfn, 'rb') as source:
            if source.read().endswith('\n'):
                newline = True
        tgt = tempfile.mkstemp()[1]
        passthrough = context if context else {}
        passthrough['salt'] = __salt__
        passthrough['grains'] = __grains__
        passthrough['pillar'] = __pillar__
        passthrough['name'] = name
        passthrough['source'] = source
        passthrough['user'] = user
        passthrough['group'] = group
        passthrough['mode'] = mode
        passthrough['env'] = env
        template = get_template(sfn, __opts__, env)
        try:
            with open(tgt, 'w+') as target:
                target.write(template.render(**passthrough))
                if newline:
                    target.write('\n')
        except UnicodeEncodeError:
            with codecs.open(tgt, encoding='utf-8', mode='w+') as target:
                target.write(template.render(**passthrough))
                if newline:
                    target.write('\n')
        return {'result': True,
                    'data': tgt}
    except:
        trb = traceback.format_exc()
        return {'result': False,
                'data': trb}
Ejemplo n.º 14
0
def render(template_file, env='', sls=''):
    '''
    Render the data passing the functions and grains into the rendering system
    '''
    if not os.path.isfile(template_file):
        return {}

    passthrough = {}
    passthrough['salt'] = __salt__
    passthrough['grains'] = __grains__
    passthrough['env'] = env
    passthrough['sls'] = sls

    template = get_template(template_file, __opts__, env)

    json_data = template.render(**passthrough)

    return json.loads(json_data)
Ejemplo n.º 15
0
def render(template_file, env='', sls=''):
    '''
    Render the data passing the functions and grains into the rendering system
    '''
    if not os.path.isfile(template_file):
        return {}

    passthrough = {}
    passthrough['salt'] = __salt__
    passthrough['grains'] = __grains__
    passthrough['env'] = env
    passthrough['sls'] = sls

    template = get_template(template_file, __opts__, env)

    json_data = template.render(**passthrough)

    return json.loads(json_data)
Ejemplo n.º 16
0
def render(template_file, env='', sls=''):
    '''
    Render the data passing the functions and grains into the rendering system
    '''
    if not os.path.isfile(template_file):
        return {}

    passthrough = {}
    passthrough['salt'] = __salt__
    passthrough['grains'] = __grains__
    passthrough['pillar'] = __pillar__
    passthrough['env'] = env
    passthrough['sls'] = sls

    template = get_template(template_file, __opts__, env)

    yaml_data = template.render(**passthrough)
    with warnings.catch_warnings(record=True) as warn_list:
        data = load(yaml_data, Loader=CustomLoader)
        if len(warn_list) > 0:
            for item in warn_list:
                log.warn("{warn} found in {file_}".format(
                        warn=item.message, file_=template_file))
        return data