Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 template variables to one line

Tags:

ansible

jinja2

Is it possible to create a jinja2 template that puts variables on one line? Something like this but instead of having two lines in the results have them comma separated.

Template:

{% for host in groups['tag_Function_logdb'] %}
elasticsearch_discovery_zen_ping_unicast_hosts = {{ host }}:9300
{% endfor %}

Results:

elasticsearch_discovery_zen_ping_unicast_hosts = 1.1.1.1:9300
elasticsearch_discovery_zen_ping_unicast_hosts = 2.2.2.2:9300

Desired Results:

elasticsearch_discovery_zen_ping_unicast_hosts = 1.1.1.1:9300,2.2.2.2:9300

Edit, this works for 2 items, better solution below:

elasticsearch_discovery_zen_ping_unicast_hosts = {% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if loop.first %},{% endif %}
{% endfor %}
like image 297
tweeks200 Avatar asked Jun 28 '16 13:06

tweeks200


3 Answers

Here's the solution that worked for me. I discovered that tweeks200's solution only works for 2 loops. This works regardless of the number of loops. Thanks to everyone here for the help.

elasticsearch_discovery_zen_ping_unicast_hosts={% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if not loop.last %},{% endif %}
{% endfor %}
like image 68
James Saint-Rossy Avatar answered Nov 20 '22 01:11

James Saint-Rossy


I was able to get this working by putting the directive I wanted before loop and then using the loop.first and - whitespace control to format the comma separated list properly.

elasticsearch_discovery_zen_ping_unicast_hosts = {% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if loop.first %},{% endif %}
{% endfor %}
like image 44
tweeks200 Avatar answered Nov 20 '22 01:11

tweeks200


Here's how you can do it:

elasticsearch_discovery_zen_ping_unicast_hosts =  

 {% for host in groups['tag_Function_logdb']  %}

    {{ host }}:9300

    {% if not groups['tag_Function_logdb'].last %}
, 
    {% endif %}

{% endfor %}
like image 1
dmitryro Avatar answered Nov 20 '22 01:11

dmitryro