How to use template module with different set of variables?

Question:

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:

I would like to find a proper way to get this variable filled by “File1” and “File2”. Something like :

where I could specify for the first templating that the variable to use is a = “File1” and for the second, b = “File2”.

Answer:

For Ansible 2.x:


For Ansible 1.x:

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 your template 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.

Leave a Reply