3
from charmhelpers.core import host
4
from charmhelpers.core import hookenv
7
def render(source, target, context, owner='root', group='root',
8
perms=0o444, templates_dir=None):
12
The `source` path, if not absolute, is relative to the `templates_dir`.
14
The `target` path should be absolute.
16
The context should be a dict containing the values to be replaced in the
19
The `owner`, `group`, and `perms` options will be passed to `write_file`.
21
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
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.
27
from jinja2 import FileSystemLoader, Environment, exceptions
30
from charmhelpers.fetch import apt_install
32
hookenv.log('Could not import jinja2, and could not import '
33
'charmhelpers.fetch to install it',
36
apt_install('python-jinja2', fatal=True)
37
from jinja2 import FileSystemLoader, Environment, exceptions
39
if templates_dir is None:
40
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
41
loader = Environment(loader=FileSystemLoader(templates_dir))
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),
50
content = template.render(context)
51
host.mkdir(os.path.dirname(target), owner, group)
52
host.write_file(target, content, owner, group, perms)