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):
41
40
this will attempt to use charmhelpers.fetch.apt_install to install it.
44
from jinja2 import ChoiceLoader, FileSystemLoader, Environment, exceptions
43
from jinja2 import FileSystemLoader, Environment, exceptions
45
44
except ImportError:
47
46
from charmhelpers.fetch import apt_install
51
50
level=hookenv.ERROR)
53
52
apt_install('python-jinja2', fatal=True)
54
from jinja2 import ChoiceLoader, FileSystemLoader, Environment, exceptions
53
from jinja2 import FileSystemLoader, Environment, exceptions
56
if template_searchpath:
58
for tmpl_dir in template_searchpath:
59
fs_loaders.append(FileSystemLoader(tmpl_dir))
60
loader = ChoiceLoader(fs_loaders)
56
template_env = Environment(loader=template_loader)
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))
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)
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)