I'm trying to use ansible to generate a file using nested templates, and I'm running into issues with
having the variables available to me in the nested templates. I'll try to explain this concisely.
File ./hosts.yml:
---
- hosts: myhosts
roles:
- role: nestedtemplate
my_configs:
- name: config1
section1:
- { type: type1, params: { path: "hi" } }
- { type: type2, params: { path: "bye" } }
Essentially, my_configs represents a list of config files to generate. For each section of the config file,
there is a list of dictionaries each containing a type (the config sub-template to use) and a params dictionary,
containing parameters to be substituted as necessary in that template.
File ./roles/nestedtemplate/tasks/main.yaml:
---
- name: nested template test
template: src=testfile_skeleton.j2
with_items: my_configs
File ./roles/nestedtemplate/templates/testfile_skeleton.j2:
# Config file skeleton
{% for input in item.section1 %}
{{ input }}
{% set incfile = 'my_' + input.type + '.conf.j2' %}
{% include incfile %}
{% endfor %}
File ./roles/nestedtemplate/templates/my_type1.j2:
---------
type1 subtemplate
File ./roles/nestedtemplate/templates/my_type2.j2:
---------
type2 subtemplate
When I run the playbook, the generated file looks like this:
# Config file skeleton
{'type': 'type1', 'params': {'path': 'hi'}}
---------
type1 subtemplate
{'type': 'type2', 'params': {'path': 'bye'}}
---------
type2 subtemplate
Note that the {{ input }} I put into the skeleton template does what I'd expect. However, any
attempt to use {{ input }} in any of the nested templates fails with an error saying that input
is undefined. Am I doing something wrong here? Is there an ansible-y way to accomplish what
I'm attempting?
Thanks in advance,
E