templatesansiblejinja2ansible-template

how to append to a list in jinja2 for ansible


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..


Solution

  • 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