23
23
def render(source, target, context, owner='root', group='root',
24
perms=0o444, templates_dir=None, encoding='UTF-8'):
24
perms=0o444, templates_dir=None, encoding='UTF-8', template_loader=None):
28
28
The `source` path, if not absolute, is relative to the `templates_dir`.
30
The `target` path should be absolute.
30
The `target` path should be absolute. It can also be `None`, in which
31
case no file will be written.
32
33
The context should be a dict containing the values to be replaced in the
37
38
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
40
The rendered template will be written to the file as well as being returned
39
43
Note: Using this requires python-jinja2; if it is not installed, calling
40
44
this will attempt to use charmhelpers.fetch.apt_install to install it.
52
56
apt_install('python-jinja2', fatal=True)
53
57
from jinja2 import FileSystemLoader, Environment, exceptions
55
if templates_dir is None:
56
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
57
loader = Environment(loader=FileSystemLoader(templates_dir))
60
template_env = Environment(loader=template_loader)
62
if templates_dir is None:
63
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
64
template_env = Environment(loader=FileSystemLoader(templates_dir))
60
template = loader.get_template(source)
67
template = template_env.get_template(source)
61
68
except exceptions.TemplateNotFound as e:
62
69
hookenv.log('Could not load template %s from %s.' %
63
70
(source, templates_dir),
64
71
level=hookenv.ERROR)
66
73
content = template.render(context)
67
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
68
host.write_file(target, content.encode(encoding), owner, group, perms)
74
if target is not None:
75
target_dir = os.path.dirname(target)
76
if not os.path.exists(target_dir):
77
# This is a terrible default directory permission, as the file
78
# or its siblings will often contain secrets.
79
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
80
host.write_file(target, content.encode(encoding), owner, group, perms)