Reputation: 11
I am trying to create a config from a template using ansible which should look like this
files:
'/opt/services':
box 1:
url: localhost:5623
box 2:
url: localhost:5623
box 3:
url: localhost:5623
I have a variable {{ box_names }}
which gives ["box 1", "box 2", "box 3", and so on]
rn my task looks like this
tasks:
- name: print the box names
debug:
msg: "box names: {{ box_names }}"
- name: Settings | Import default config
template:
src: test.yaml.j2
dest: "/opt/test/config.yaml"
owner: "{{ user.name }}"
group: "{{ user.name }}"
mode: 0775
loop: "{{ box_names }}"
and my config template looks like
files:
'/opt/services':
{{ item }}:
url: localhost:5623
but the final template only shows box 1 and not box 2 or box 3. how do I make the config show all the items of the loop?
Upvotes: 1
Views: 179
Reputation: 68229
Create the dictionary
files:
/opt/services: "{{ dict(box_names|
product([{'url': 'localhost:5623'}])) }}"
gives
files:
/opt/services:
box 1:
url: localhost:5623
box 2:
url: localhost:5623
box 3:
url: localhost:5623
Then, the template is trivial
shell> cat test.yaml.j2
files:
{{ files|to_nice_yaml }}
Upvotes: 0
Reputation: 17037
use the loop inside the template j2 file:
files:
'/opt/services':
{% for box in box_names %}
{{box}}:
url: localhost:5623
{% endfor %}
The task:
- name: Settings | Import default config
template:
src: test.yaml.j2
dest: "/opt/test/config.yaml"
owner: "{{ user.name }}"
group: "{{ user.name }}"
mode: 0775
result:
files:
'/opt/services':
box 1:
url: localhost:5623
box 2:
url: localhost:5623
box 3:
url: localhost:5623
if you want ot use this result as var file, i suggest you to add quotes around key in the template file
Upvotes: 1