From d532ab05ab8e8da3a598a385100852e491e98f07 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 26 Sep 2017 11:50:57 -0700 Subject: [PATCH] fixes issue where filter wouldn't error on undefined var (#30921) The filter will now correctly error on an undefined variable when trying to template the key `value` (cherry picked from commit 909100bd2cad4dfc60e07e57d0404d33726db2bf) --- lib/ansible/module_utils/network_common.py | 12 +++--------- lib/ansible/plugins/filter/network.py | 4 +++- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/lib/ansible/module_utils/network_common.py b/lib/ansible/module_utils/network_common.py index 7d6f2be12a..49e608032e 100644 --- a/lib/ansible/module_utils/network_common.py +++ b/lib/ansible/module_utils/network_common.py @@ -35,7 +35,7 @@ from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.basic import AnsibleFallbackNotFound try: - from jinja2 import Environment + from jinja2 import Environment, StrictUndefined from jinja2.exceptions import UndefinedError HAS_JINJA2 = True except ImportError: @@ -342,11 +342,12 @@ class Template: raise ImportError("jinja2 is required but does not appear to be installed. " "It can be installed using `pip install jinja2`") - self.env = Environment() + self.env = Environment(undefined=StrictUndefined) self.env.filters.update({'ternary': ternary}) def __call__(self, value, variables=None, fail_on_undefined=True): variables = variables or {} + if not self.contains_vars(value): return value @@ -365,13 +366,6 @@ class Template: else: return None - def can_template(self, tmpl): - try: - self(tmpl) - return True - except: - return False - def contains_vars(self, data): if isinstance(data, string_types): for marker in (self.env.block_start_string, self.env.variable_start_string, self.env.comment_start_string): diff --git a/lib/ansible/plugins/filter/network.py b/lib/ansible/plugins/filter/network.py index 2da2b52d92..fde29ef008 100644 --- a/lib/ansible/plugins/filter/network.py +++ b/lib/ansible/plugins/filter/network.py @@ -87,9 +87,11 @@ def parse_cli(output, tmpl): for name, attrs in iteritems(spec['keys']): value = attrs['value'] - if template.can_template(value): + try: variables = spec.get('vars', {}) value = template(value, variables) + except: + pass if 'start_block' in attrs and 'end_block' in attrs: start_block = re.compile(attrs['start_block'])