3
from charmhelpers.core import host
4
from charmhelpers.core import hookenv
7
def render(source, target, context, owner='root', group='root', perms=0444, templates_dir=None):
11
The `source` path, if not absolute, is relative to the `templates_dir`.
13
The `target` path should be absolute.
15
The context should be a dict containing the values to be replaced in the
18
The `owner`, `group`, and `perms` options will be passed to `write_file`.
20
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
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.
26
from jinja2 import FileSystemLoader, Environment, exceptions
29
from charmhelpers.fetch import apt_install
31
hookenv.log('Could not import jinja2, and could not import '
32
'charmhelpers.fetch to install it',
35
apt_install('python-jinja2', fatal=True)
36
from jinja2 import FileSystemLoader, Environment, exceptions
38
if templates_dir is None:
39
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
40
loader = Environment(loader=FileSystemLoader(templates_dir))
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),
49
content = template.render(context)
50
host.mkdir(os.path.dirname(target))
51
host.write_file(target, content, owner, group, perms)