Merge pull request #222 from ChrisMacNaughton/require-env-vars

Use jinja2's StrinctUndefined to make template variables mandatory
This commit is contained in:
David Ames
2019-04-22 10:29:49 -07:00
committed by GitHub
2 changed files with 27 additions and 5 deletions

View File

@@ -128,6 +128,23 @@ class TestCharmLifecycleDeploy(ut_utils.BaseTestCase):
template_mock,
'/tmp/special-dir/my_overlay.yaml')
def test_template_missing_required_variables(self):
self.patch_object(lc_deploy, 'get_template_overlay_context')
self.get_template_overlay_context.return_value = {}
self.patch_object(lc_deploy.sys, 'exit')
self.patch_object(lc_deploy.logging, 'error')
jinja2_env = lc_deploy.get_jinja2_env()
template = jinja2_env.from_string('{{required_variable}}')
m = mock.mock_open()
with mock.patch('zaza.charm_lifecycle.deploy.open', m, create=True):
lc_deploy.render_template(template, '/tmp/mybundle.yaml')
m.assert_called_once_with('/tmp/mybundle.yaml', 'w')
self.error.assert_called_once_with(
"Template error. You may be missing"
" a mandatory environment variable : "
"'required_variable' is undefined")
self.exit.assert_called_once_with(1)
def test_render_overlay_no_template(self):
self.patch_object(lc_deploy, 'get_template')
self.get_template.return_value = None

View File

@@ -118,7 +118,8 @@ def get_jinja2_env():
"""
template_dir = get_overlay_template_dir()
return jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir)
loader=jinja2.FileSystemLoader(template_dir),
undefined=jinja2.StrictUndefined
)
@@ -158,10 +159,14 @@ def render_template(template, target_file):
:param target_file: File name for rendered template
:type target_file: str
"""
with open(target_file, "w") as fh:
fh.write(
template.render(get_template_overlay_context()))
try:
with open(target_file, "w") as fh:
fh.write(
template.render(get_template_overlay_context()))
except jinja2.exceptions.UndefinedError as e:
logging.error("Template error. You may be missing"
" a mandatory environment variable : {}".format(e))
sys.exit(1)
logging.info("Rendered template '{}' to file '{}'".format(template,
target_file))