From 56148291e99ebac0979e4866e26fefaf88fec024 Mon Sep 17 00:00:00 2001 From: Dag Wieers Date: Fri, 12 Aug 2016 15:29:54 +0200 Subject: [PATCH] Emit warnings when safe_eval() raises a SyntaxError or other Exception (#14304) This change is related to reported issue #14291 and pull request #14293. Without the fix from #14293, this change will emit a warning as shown below, on the following playbook: ``yaml --- - hosts: localhost gather_facts: no vars: works: key1: 'string' key2: 1234 fails: key1: 'string' key2: 1234 key3: false tasks: - debug: msg={{ works | to_json }} - debug: msg={{ fails | to_json }} ``` On error, this results in a proper warning: ``` [dag@moria ansible.dag]$ ansible-playbook test49.yml PLAY *************************************************************************** TASK [debug] ******************************************************************* ok: [localhost] => { "msg": { "key1": "string", "key2": 1234 } } TASK [debug] ******************************************************************* [WARNING]: Error in expression "{"key3": false, "key2": 1234, "key1": "string"}". (name 'false' is not defined) ok: [localhost] => { "msg": "{\"key3\": false, \"key2\": 1234, \"key1\": \"string\"}" } PLAY RECAP ********************************************************************* localhost : ok=2 changed=0 unreachable=0 failed=0 ``` --- lib/ansible/template/safe_eval.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/ansible/template/safe_eval.py b/lib/ansible/template/safe_eval.py index d82373a6fb9..845216b621d 100644 --- a/lib/ansible/template/safe_eval.py +++ b/lib/ansible/template/safe_eval.py @@ -26,6 +26,12 @@ from ansible.compat.six.moves import builtins from ansible import constants as C from ansible.plugins import filter_loader, test_loader +try: + from __main__ import display +except ImportError: + from ansible.utils.display import Display + display = Display() + def safe_eval(expr, locals={}, include_exceptions=False): ''' This is intended for allowing things like: @@ -131,13 +137,14 @@ def safe_eval(expr, locals={}, include_exceptions=False): else: return result except SyntaxError as e: + display.warning('SyntaxError in safe_eval() on expr: %s (%s)' % (expr, e)) # special handling for syntax errors, we just return # the expression string back as-is if include_exceptions: return (expr, None) return expr except Exception as e: + display.warning('Exception in safe_eval() on expr: %s (%s)' % (expr, e)) if include_exceptions: return (expr, e) return expr -