My use case is the following :
I have a template file, and I would like to create 2 different files from that template, with the variables being filled by a different set of variables for each file.
For example, lets say I want to template the file containing the line:
mkdir -p {{myTemplateVariable}}
I would like to find a proper way to get this variable filled by "File1" and "File2". Something like :
- name: template test 1
template:
src=myTemplateFile
dest=result1
- name: template test 2
template:
src=myTemplateFile
dest=result2
where I could specify for the first templating that the variable to use is a = "File1" and for the second, b = "File2".
I did it in this way.
In tasks/main.yml
and in vars/main.yml
and in templates/myTemplateFile.j2
Hope this solves your problem.
IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.
In the template I have:
With Ansible 2.x you can use
vars:
with tasks.Template
test.j2
:Playbook:
This will pass different
myTemplateVariable
values into test.j2.I had a similar problem to solve, here is a simple solution of how to pass variables to template files, the trick is to write the template file taking advantage of the variable. You need to create a dictionary (list is also possible), which holds the set of variables corresponding to each of the file. Then within the template file access them.
see below:
the playbook
This is a solution/hack I'm using:
tasks/main.yml:
vars/main.yml
templates/test.j2:
After running this, you get
this is var_a
in /tmp/templateA andthis is var_b
in /tmp/templateB.Basically you abuse
with_items
to render the template with each item in the one-item list. This works because you can control what the list is when usingwith_items
.The downside of this is that you have to use
item
as the variable name in you template.If you want to pass more than one variable this way, you can dicts as your list items like this:
and then refer to them in your template like this:
Unfortunately the
template
module does not support passing variables to it, which can be used inside the template. There was a feature request but it was rejected.I can think of two workarounds:
1. Include
The
include
statement supports passing variables. So you could have yourtemplate
task inside an extra file and include it twice with appropriate parameters:my_include.yml:
main.yml:
2. Re-define myTemplateVariable
Another way would be to simply re-define myTemplateVariable right before every
template
task.