~landscape/charms/trusty/neutron-api-odl-vpp/trunk

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/templating.py

  • Committer: Liam Young
  • Date: 2015-11-03 13:42:27 UTC
  • mfrom: (4.1.1 neutron-api-odl)
  • Revision ID: liam.young@canonical.com-20151103134227-pnazu50qwdizbudp
Sync from lp:charm-helpers and fix services.py to fit with it

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
 
23
23
def render(source, target, context, owner='root', group='root',
24
 
           perms=0o444, templates_dir=None, encoding='UTF-8',
25
 
           template_searchpath=None):
 
24
           perms=0o444, templates_dir=None, encoding='UTF-8', template_loader=None):
26
25
    """
27
26
    Render a template.
28
27
 
41
40
    this will attempt to use charmhelpers.fetch.apt_install to install it.
42
41
    """
43
42
    try:
44
 
        from jinja2 import ChoiceLoader, FileSystemLoader, Environment, exceptions
 
43
        from jinja2 import FileSystemLoader, Environment, exceptions
45
44
    except ImportError:
46
45
        try:
47
46
            from charmhelpers.fetch import apt_install
51
50
                        level=hookenv.ERROR)
52
51
            raise
53
52
        apt_install('python-jinja2', fatal=True)
54
 
        from jinja2 import ChoiceLoader, FileSystemLoader, Environment, exceptions
 
53
        from jinja2 import FileSystemLoader, Environment, exceptions
55
54
 
56
 
    if template_searchpath:
57
 
        fs_loaders = []
58
 
        for tmpl_dir in template_searchpath:
59
 
            fs_loaders.append(FileSystemLoader(tmpl_dir))
60
 
        loader = ChoiceLoader(fs_loaders) 
 
55
    if template_loader:
 
56
        template_env = Environment(loader=template_loader)
61
57
    else:
62
58
        if templates_dir is None:
63
59
            templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
64
 
        loader = Environment(loader=FileSystemLoader(templates_dir))
 
60
        template_env = Environment(loader=FileSystemLoader(templates_dir))
65
61
    try:
66
62
        source = source
67
 
        template = loader.get_template(source)
 
63
        template = template_env.get_template(source)
68
64
    except exceptions.TemplateNotFound as e:
69
65
        hookenv.log('Could not load template %s from %s.' %
70
66
                    (source, templates_dir),
71
67
                    level=hookenv.ERROR)
72
68
        raise e
73
69
    content = template.render(context)
74
 
    host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
 
70
    target_dir = os.path.dirname(target)
 
71
    if not os.path.exists(target_dir):
 
72
        # This is a terrible default directory permission, as the file
 
73
        # or its siblings will often contain secrets.
 
74
        host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
75
75
    host.write_file(target, content.encode(encoding), owner, group, perms)