~jshieh/charms/trusty/xcat/1428813

« back to all changes in this revision

Viewing changes to charms/trusty/gpfs/lib/charmhelpers/core/templating.py

  • Committer: Michael Chase-Salerno
  • Date: 2015-01-16 16:16:45 UTC
  • Revision ID: bratac@linux.vnet.ibm.com-20150116161645-wvh0sllwqgyilelw
Initial GPFS charm

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
 
 
3
from charmhelpers.core import host
 
4
from charmhelpers.core import hookenv
 
5
 
 
6
 
 
7
def render(source, target, context, owner='root', group='root',
 
8
           perms=0o444, templates_dir=None):
 
9
    """
 
10
    Render a template.
 
11
 
 
12
    The `source` path, if not absolute, is relative to the `templates_dir`.
 
13
 
 
14
    The `target` path should be absolute.
 
15
 
 
16
    The context should be a dict containing the values to be replaced in the
 
17
    template.
 
18
 
 
19
    The `owner`, `group`, and `perms` options will be passed to `write_file`.
 
20
 
 
21
    If omitted, `templates_dir` defaults to the `templates` folder in the charm.
 
22
 
 
23
    Note: Using this requires python-jinja2; if it is not installed, calling
 
24
    this will attempt to use charmhelpers.fetch.apt_install to install it.
 
25
    """
 
26
    try:
 
27
        from jinja2 import FileSystemLoader, Environment, exceptions
 
28
    except ImportError:
 
29
        try:
 
30
            from charmhelpers.fetch import apt_install
 
31
        except ImportError:
 
32
            hookenv.log('Could not import jinja2, and could not import '
 
33
                        'charmhelpers.fetch to install it',
 
34
                        level=hookenv.ERROR)
 
35
            raise
 
36
        apt_install('python-jinja2', fatal=True)
 
37
        from jinja2 import FileSystemLoader, Environment, exceptions
 
38
 
 
39
    if templates_dir is None:
 
40
        templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
 
41
    loader = Environment(loader=FileSystemLoader(templates_dir))
 
42
    try:
 
43
        source = source
 
44
        template = loader.get_template(source)
 
45
    except exceptions.TemplateNotFound as e:
 
46
        hookenv.log('Could not load template %s from %s.' %
 
47
                    (source, templates_dir),
 
48
                    level=hookenv.ERROR)
 
49
        raise e
 
50
    content = template.render(context)
 
51
    host.mkdir(os.path.dirname(target), owner, group)
 
52
    host.write_file(target, content, owner, group, perms)