From 2aa0f366d22b3681c4483c324073257dce473f7f Mon Sep 17 00:00:00 2001 From: Pilou Date: Thu, 29 Nov 2018 15:56:23 +0100 Subject: [PATCH] templar: ensure that exceptions are handled, fix 'AttributeError' (#48792) * templar: ensure that exceptions are handled * Fix AttributeError: object has no attribute 'message' 'message' attribute is deprecated since Python 2.6 and not available with Python 3. Simple reproducer: - hosts: localhost vars: not_json: "{{ 'test str' | from_json }}" tasks: - command: "echo {{ not_json }}" (cherry picked from commit 62c05033d604dbdc74aa79995e04fa119d1f57c4) --- changelogs/fragments/48792-templar-fix-AttributeError.yml | 2 ++ lib/ansible/template/vars.py | 2 +- test/units/template/test_templar.py | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/48792-templar-fix-AttributeError.yml diff --git a/changelogs/fragments/48792-templar-fix-AttributeError.yml b/changelogs/fragments/48792-templar-fix-AttributeError.yml new file mode 100644 index 0000000000..0a69b936f3 --- /dev/null +++ b/changelogs/fragments/48792-templar-fix-AttributeError.yml @@ -0,0 +1,2 @@ +bugfixes: + - Fix AttributeError (Python 3 only) when an exception occurs while rendering a template diff --git a/lib/ansible/template/vars.py b/lib/ansible/template/vars.py index a645aafade..716e410f61 100644 --- a/lib/ansible/template/vars.py +++ b/lib/ansible/template/vars.py @@ -108,7 +108,7 @@ class AnsibleJ2Vars(Mapping): except AnsibleUndefinedVariable: raise except Exception as e: - msg = getattr(e, 'message') or to_native(e) + msg = getattr(e, 'message', None) or to_native(e) raise AnsibleError("An unhandled exception occurred while templating '%s'. " "Error was a %s, original message: %s" % (to_native(variable), type(e), msg)) diff --git a/test/units/template/test_templar.py b/test/units/template/test_templar.py index cbc1417c44..3e9eb66627 100644 --- a/test/units/template/test_templar.py +++ b/test/units/template/test_templar.py @@ -50,6 +50,7 @@ class BaseTemplar(object): some_unsafe_var=wrap_var("unsafe_blip"), some_static_unsafe_var=wrap_var("static_unsafe_blip"), some_unsafe_keyword=wrap_var("{{ foo }}"), + str_with_error="{{ 'str' | from_json }}", ) self.fake_loader = DictDataLoader({ "/path/to/my_file.txt": "foo\n", @@ -200,6 +201,10 @@ class TestTemplarTemplate(BaseTemplar, unittest.TestCase): self.templar.template, data) + def test_template_with_error(self): + """Check that AnsibleError is raised, fail if an unhandled exception is raised""" + self.assertRaises(AnsibleError, self.templar.template, "{{ str_with_error }}") + class TestTemplarCleanData(BaseTemplar, unittest.TestCase): def test_clean_data(self):