Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible jinja - If loop last without newline

I'm having problem with ansible jinja templating. Basically i just need to list down the server_name is more readable format.

This is the variable that i defined in groups/all.yml

server_name:
  - domain1.mydomain.com
  - domain2.mydomain.com
  - domain3.mydomain.com
  - domain4.mydomain.com

And this is my template for myvhost.conf.j2

server_name     {% for name in server_name -%}
                  {{ name }}
                {% if loop.last -%};{%- endif -%}{% endfor %}

And the result is:

server_name     domain1.mydomain.com
                domain2.mydomain.com
                domain3.mydomain.com
                domain4.mydomain.com
                ;

Expected output:

server_name     domain1.mydomain.com
                domain2.mydomain.com
                domain3.mydomain.com
                domain4.mydomain.com;

I have tried several combination for the templating with whitespace control or indent but it messed up the result. Please advise kindly

like image 445
AlamHo Avatar asked Oct 17 '25 11:10

AlamHo


1 Answers

You want to print either a newline character followed by 16 spaces, or ;, after the variable value, so it is a natural requirement for an if-else statement:

server_name     {% for name in server_name -%}
                  {{ name }}
                {%- if not loop.last %}

                {% else %};{% endif %}{% endfor %}
like image 159
techraf Avatar answered Oct 19 '25 06:10

techraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!