From ccbdd6229a247e51cba15d8913687f03580a80ac Mon Sep 17 00:00:00 2001 From: Yannig Perre Date: Wed, 4 Nov 2015 22:16:14 +0100 Subject: [PATCH] Use static vars when computing host vars known to be static (inventory_hostname, inventory_dir etc.). --- lib/ansible/template/__init__.py | 7 +++++-- lib/ansible/vars/hostvars.py | 9 ++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py index 31d60a1d3d1..8f9324752e0 100644 --- a/lib/ansible/template/__init__.py +++ b/lib/ansible/template/__init__.py @@ -268,7 +268,7 @@ class Templar: # Clearing cache self._cached_result = {} - def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, convert_data=True): + def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, convert_data=True, static_vars = ['']): ''' Templates (possibly recursively) any given data as input. If convert_bare is set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}') @@ -340,7 +340,10 @@ class Templar: # we don't use iteritems() here to avoid problems if the underlying dict # changes sizes due to the templating, which can happen with hostvars for k in variable.keys(): - d[k] = self.template(variable[k], preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides) + if k not in static_vars: + d[k] = self.template(variable[k], preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides) + else: + d[k] = variable[k] return d else: return variable diff --git a/lib/ansible/vars/hostvars.py b/lib/ansible/vars/hostvars.py index bba46075efe..b4cd5eeaf48 100644 --- a/lib/ansible/vars/hostvars.py +++ b/lib/ansible/vars/hostvars.py @@ -28,6 +28,13 @@ from ansible import constants as C from ansible.inventory.host import Host from ansible.template import Templar +STATIC_VARS = [ + 'inventory_hostname', 'inventory_hostname_short', + 'inventory_file', 'inventory_dir', 'playbook_dir', + 'ansible_play_hosts', 'play_hosts', 'groups', 'ungrouped', 'group_names', + 'ansible_version', 'omit', 'role_names' +] + try: from hashlib import sha1 except ImportError: @@ -81,7 +88,7 @@ class HostVars(collections.Mapping): result = self._cached_result[sha1_hash] else: templar = Templar(variables=data, loader=self._loader) - result = templar.template(data, fail_on_undefined=False) + result = templar.template(data, fail_on_undefined=False, static_vars=STATIC_VARS) self._cached_result[sha1_hash] = result return result