carrotcakeslayer
carrotcakeslayer

Reputation: 998

How to add separators in Jinja2

I need to get a list of IPs like this one (values in quotes,comma separated and no spaces).

['172.16.1.67','172.16.1.68','172.16.1.69']

To do so, I'm trying to call for a jinja2 template in my playbook. The content of the template is:

[{% for servidor in groups['servidores'] %}{{ hostvars[servidor].ansible_host}}{% endfor %}]

This template is generating this string:

[172.16.1.67172.16.1.68172.16.1.69]

I tried to use filters and things I found but no matter how I tried, I end up with errors (as most of answers I found assume that the reader know how to apply the provided solution which is not my case). My guess is that I should apply a "join" filter, but I don't know how to do it.

Could you please help me?

Thanks!

Upvotes: 1

Views: 760

Answers (1)

blhsing
blhsing

Reputation: 106435

You can format the IPs with quotes and append them to a list first before joining them with ',' in the output:

{%- set ips = [] -%}
{%- for servidor in groups['servidores'] %}
    {% do ips.append("'%s'" | format(hostvars[servidor].ansible_host)) %}
{% endfor -%}
[{{ ips | join(',') }}]

Upvotes: 2

Related Questions