Amjad Hussain Syed
Amjad Hussain Syed

Reputation: 1040

how to pass ansible group_vars array to jinja template

I'm trying to template a python script using ansible jinja2. When I pass the iterated item to the template to further generate a python dictionary is not working.

Thanks in advance for any help!.

[group_vars]
backups:
- sap

sap:
- db_host: sadf
- db_name: xyz
- db_user: xzzx
- db_pass: alskdf

ansible template looks like:

- name: transfer backup script file
  template:
    src: backup.py.j2
    dest: "{{ item }}_backup.py"
    mode: 0755
  with_items:
    - "{{ backups }}"

jinja python template looks like:

dbs = {
  {% for mongo_d in item %}

    "{{ mongo_d.db_name }}" :
    {
    "db_host": "{{ mongo_d.db_host }}",
    "db_user": "{{ mongo_d.db_user }}",
    "db_password": "{{ mongo_d.db_password }}",
 ]},

 {% endfor %}

failing with error:

item: sap
  msg: 'AnsibleUndefinedVariable: ''unicode object'' has no attribute ''db_name'''

Upvotes: 0

Views: 2132

Answers (1)

techraf
techraf

Reputation: 68469

Your data structure is cumbersome, use a dictionary instead of a list with single key-value pairs:

backups:
  - sap

sap:
  db_host: sadf
  db_name: xyz
  db_user: xzzx
  db_password: alskdf

You don't need to iterate inside the template.

The task:

- name: transfer backup script file
  template:
    src: backup.py.j2
    dest: "{{ item }}_backup.py"
    mode: 0755
  with_items:
    - "{{ backups }}"
  vars:
    mongo_d: "{{ lookup('vars', item) }}"

The template:

dbs = {
    "{{ mongo_d.db_name }}" :
    {
    "db_host": "{{ mongo_d.db_host }}",
    "db_user": "{{ mongo_d.db_user }}",
    "db_password": "{{ mongo_d.db_password }}",
 ]},

I corrected db_password typo, but for inconsistencies in the template, I left them as posted in the question.

Upvotes: 1

Related Questions