Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append to a list in jinja2 for ansible

Tags:

Below is the jinja2 template that i wrote to use in ansible.

{% set port = 1234 %} {% set server_ip = [] %} {% for ip in host_ip  %} {% do server_ip.append({{ ip }}:{{ port }}) %} {% endfor %} {% server_ip|join(', ') %} 

Below is the my desired output:

devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234 

But when i am running the ansible playbook, it is throwing the error as below:

"AnsibleError: teme templating string: Encountered unknown tag 'do'. Jinja was looking for th: 'endfor' or 'else' 

Any help would be appreciated..

like image 306
learning fun Avatar asked Apr 02 '18 22:04

learning fun


People also ask

What is j2 Jinja2 used for in Ansible?

Ansible uses the jinja2 templates for template files. Jinja2 is a modern and designer-friendly templating language for Python frameworks. It is widely used for dynamic file generation based on its parameter.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

What is Autoescape in Jinja2?

B701: Test for not auto escaping in jinja2When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.


1 Answers

Try below code:

{% set port = '1234' %} {% set server_ip = [] %} {% for ip in host_ip  %} {{ server_ip.append( ip+":"+port ) }} {% endfor %} {{ server_ip|join(',') }} 

You ll get:

192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234

like image 119
Sheshananda Naidu Avatar answered Sep 19 '22 10:09

Sheshananda Naidu