~evarlast/charms/trusty/elasticsearch/add-logs-relation

« back to all changes in this revision

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

  • Committer: Michael Nelson
  • Date: 2014-11-06 02:48:04 UTC
  • mfrom: (35.1.8 firewall_optional)
  • Revision ID: michael.nelson@canonical.com-20141106024804-uxduhm2huet147vi
[r=simondavy][bugs=1386664,1376396] Bug fix for firewall on ec2 and enable firewall to be configured off (as well as update of tests and charmhelpers).

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