How to pass item.src to a template in Ansible

ansibletemplate

I have a Jinja2 template and I want to pass args to it from my vars/main.yml.

For each set of vars, I need to generate a separate file on the remote server.

My vars/main.yml has the following structure:

List:
  - { src: [
        classPath1: xxx,
        classPath2: xxx, 
        contxtHost: xxx,
        logDir: xxx, 
        contxtRegion: xxx,
        .... 
        ],
      dest: xxxx 
    }
  - { src: [
        xxxx
        ], 
      dest: xxxx 
    }

in my playbook task is defined as below:

  - name: testing templates 
    template: "src=templates/sampletest.j2 
               dest=/path/in/Server/{{ item.dest }}
               owner=app 
               group=app 
               mode=0644"
    with_items: '{{ List }}'

How do I pass item.src to my template?

Note: I am trying to generate multiple files based on each set of vars item.src and file name is item.dest using with_items.

Best Answer

Just reference them in the templates/sampletest.j2, for example:

# start of the template
classPath1 is {{ item.src[0].classPath1 }}
classPath2 is {{ item.src[1].classPath2 }}
contxtHost is {{ item.src[2].contxtHost }}
...
# end of the template

For each item on the List the template will be parsed and saved to a file defined in dest.


Now, the problem is that your vars/main.yml file defines src as a list (square brackets) of dictionaries, each containing a single key-value pair (with the key named differently in each item on the list), so:

  • first, you need to reference the list item by its order (e.g. src[1])
  • then, you need to reference the key which is defined in that particular item (e.g. classPath2 for and only for src[1]).