From 20b07169482a4bca033dad97c921cc03f0ed5890 Mon Sep 17 00:00:00 2001 From: Abhijit Menon-Sen Date: Wed, 2 Aug 2017 09:29:27 +0530 Subject: [PATCH] Allow variables to be passed in to template lookup plugin (#18662) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This allows a single template to be evaluated with different values in the same task. For example, with a template like 'x:{{a}}', one could do something like this: - foo: a: "{{ lookup('template', 'x.j2', template_vars=dict(a=foo[item])) }}" b: "{{ lookup('template', 'x.j2', template_vars=dict(a=bar[item])) }}" with_items: - x - y …and "a" and "b" would expand to different strings based on what we passed in to the template lookup. --- docs/docsite/rst/playbooks_lookups.rst | 3 +++ lib/ansible/plugins/lookup/template.py | 13 +++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/docsite/rst/playbooks_lookups.rst b/docs/docsite/rst/playbooks_lookups.rst index 001faed2116..278429057e9 100644 --- a/docs/docsite/rst/playbooks_lookups.rst +++ b/docs/docsite/rst/playbooks_lookups.rst @@ -556,6 +556,9 @@ Here are some examples:: - debug: msg="{{ lookup('template', './some_template.j2') }} is a value from evaluation of this template" + # Since 2.4, you can pass in variables during evaluation + - debug: msg="{{ lookup('template', './some_template.j2', template_vars=dict(x=42)) }} is evaluated with x=42" + - name: loading a json file from a template as a string debug: msg="{{ lookup('template', './some_json.json.j2', convert_data=False) }} is a value from evaluation of this template" diff --git a/lib/ansible/plugins/lookup/template.py b/lib/ansible/plugins/lookup/template.py index 27a4bd2486f..a435843ed2a 100644 --- a/lib/ansible/plugins/lookup/template.py +++ b/lib/ansible/plugins/lookup/template.py @@ -36,6 +36,7 @@ class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): convert_data_p = kwargs.get('convert_data', True) + lookup_template_vars = kwargs.get('template_vars', {}) ret = [] for term in terms: @@ -62,10 +63,14 @@ class LookupModule(LookupBase): searchpath = [self._loader._basedir, os.path.dirname(lookupfile)] self._templar.environment.loader.searchpath = searchpath - # add ansible 'template' vars - temp_vars = variables.copy() - temp_vars.update(generate_ansible_template_vars(lookupfile)) - self._templar.set_available_variables(temp_vars) + # The template will have access to all existing variables, + # plus some added by ansible (e.g., template_{path,mtime}), + # plus anything passed to the lookup with the template_vars= + # argument. + vars = variables.copy() + vars.update(generate_ansible_template_vars(lookupfile)) + vars.update(lookup_template_vars) + self._templar.set_available_variables(vars) # do the templating res = self._templar.template(template_data, preserve_trailing_newlines=True,