How to use template module with different set of variables?

Kestemont Max picture Kestemont Max · Jun 30, 2015 · Viewed 111k times · Source

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".

Answer

Konstantin Suvorov picture Konstantin Suvorov · Jul 29, 2016

With Ansible 2.x you can use vars: with tasks.

Template test.j2:

mkdir -p {{myTemplateVariable}}

Playbook:

- template: src=test.j2 dest=/tmp/File1
  vars:
    myTemplateVariable: myDirName

- template: src=test.j2 dest=/tmp/File2
  vars:
    myTemplateVariable: myOtherDir

This will pass different myTemplateVariable values into test.j2.