Skip to content

Commit 05c363c

Browse files
committed
util: avoid overwriting config_file with None on failed jinja render
When render_jinja_payload_from_file returns None (e.g. due to an undefined attribute error), read_conf previously assigned config_file to None, causing load_yaml to crash with an AttributeError. Only update config_file when a valid rendered payload is returned. Fixes GH-7007
1 parent 04eacd0 commit 05c363c

2 files changed

Lines changed: 26 additions & 7 deletions

File tree

cloudinit/util.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -327,17 +327,19 @@ def read_conf(fname, *, instance_data_file=None) -> Dict:
327327

328328
if instance_data_file and os.path.exists(instance_data_file):
329329
try:
330-
config_file = render_jinja_payload_from_file(
330+
rendered_config = render_jinja_payload_from_file(
331331
config_file,
332332
fname,
333333
instance_data_file,
334334
)
335-
LOG.debug(
336-
"Applied instance data in '%s' to "
337-
"configuration loaded from '%s'",
338-
instance_data_file,
339-
fname,
340-
)
335+
if rendered_config is not None:
336+
config_file = rendered_config
337+
LOG.debug(
338+
"Applied instance data in '%s' to "
339+
"configuration loaded from '%s'",
340+
instance_data_file,
341+
fname,
342+
)
341343
except JinjaSyntaxParsingException as e:
342344
LOG.warning(
343345
"Failed to render templated yaml config file '%s'. %s",

tests/unittests/test_util.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,23 @@ def test_read_conf_with_failed_instance_data_json(self, mocker, caplog):
480480
assert "Could not apply Jinja template" in caplog.text
481481
assert conf == {"a": "{{c}}"}
482482

483+
def test_read_conf_with_failed_jinja_render_undefined_attribute(
484+
self, mocker, caplog
485+
):
486+
mocker.patch("os.path.exists", return_value=True)
487+
mocker.patch(
488+
"cloudinit.util.load_text_file",
489+
return_value='## template: jinja\n{"a": "{{ ds.meta_data.placement.region }}"}',
490+
)
491+
mocker.patch(
492+
"cloudinit.handlers.jinja_template.load_text_file",
493+
return_value='{"ds": {"meta_data": {}}}',
494+
)
495+
conf = util.read_conf("cfg_path", instance_data_file="vars_path")
496+
assert "Ignoring jinja template for cfg_path" in caplog.text
497+
assert conf == {"a": "{{ ds.meta_data.placement.region }}"}
498+
499+
483500
@pytest.mark.parametrize(
484501
"template",
485502
[

0 commit comments

Comments
 (0)