Reputation: 23
I want to create multiple in ansible loop with jinja template, like that :
template_a
name = a
username = c
template_b
name = b
username = d
playbook.yml
- name: Create file from jinja
template:
src: "jinja.j2"
dest: "template_{{ item }}"
owner: "root"
group: "root"
with_items: "{{ jinja_var }}"
variables.yml
jinja_var:
a: c
b: d
jinja.j2
{% for (key,value) in jinja_var.iteritems() %}
name = {{ key }}
username = {{ value }}
{% endfor %}
I have got two same files :
name = a
username = 1
name = b
username = 2
Upvotes: 0
Views: 1964
Reputation: 1218
There are several ways to achieve the above mentioned output. Nothing complex though, with minor changes in the playbook task
and jinja
template would fix your issue.
When we add a for loop to iterate it would add each and every dictionary object present in the variable to the destination file. So, by directly adding item
inside jinja
and passing the with_dict
to the task would mitigate the above mentioned problem.
playbook.yml
- name: Create file from jinja
template:
src: "jinja.j2"
dest: "template_{{ item.key }}"
owner: "root"
group: "root"
with_dict: "{{ jinja_var }}"
jinja.j2
name = {{ item.key }}
username = {{ item.value }}
Output
template_a
name = a
username = c
template_b
name = b
username = d
Upvotes: 1