Updating variable in Ninja for loop

19 views
Skip to first unread message

Willem D'Haese

unread,
Feb 24, 2018, 8:08:14 AM2/24/18
to Ansible Project
Hello,

I'm trying to create a new string from the keys of a dictionary in a Ninja 2 template. But the variable I'm updating in the for loop seems to reset when the for loop finishes... The following piece of template is just a test to try demonstrate my issue:

{% set ssh_allowusers = 'root' %}
{% for x in dictusers %}
{{ssh_allowusers }} + {{ x }}
{% set ssh_allowusers = ssh_allowusers ~ ' ' ~ x %}
{{ssh_allowusers }}
{% endfor %}
Post Loop: {{ssh_allowusers }}

dict_users:

dictusers:
  willemdh
:
    shell
: /bin/zsh
    groups
: wheel
    shortname
: Willem
  ansi
:
    shell
: /bin/sh
    groups
: sysusers,wheel
    shortname
: Willem

But output is:

root + ansi
root ansi
root ansi
+ willemdh
root ansi willemdh
Post Loop: root

Why would the variable reset to 'root' after the loop? 

Grtz

Willem

Kai Stian Olstad

unread,
Feb 24, 2018, 8:47:29 AM2/24/18
to ansible...@googlegroups.com
On 24.02.2018 14:08, Willem D'Haese wrote:
> I'm trying to create a new string from the keys of a dictionary in a
> Ninja

You probably mean Jinja and not Ninja ;-)


> {% set ssh_allowusers = 'root' %}
> {% for x in dictusers %}
> {{ssh_allowusers }} + {{ x }}
> {% set ssh_allowusers = ssh_allowusers ~ ' ' ~ x %}
> {{ssh_allowusers }}
> {% endfor %}
> Post Loop: {{ssh_allowusers }}
>
> dict_users:
>
> dictusers:
> willemdh:
> shell: /bin/zsh
> groups: wheel
> shortname: Willem
> ansi:
> shell: /bin/sh
> groups: sysusers,wheel
> shortname: Willem
>
> But output is:
>
> root + ansi
> root ansi
> root ansi + willemdh
> root ansi willemdh
> Post Loop: root
>
> Why would the variable reset to 'root' after the loop?

A variable set in a block is not available outside the block.
You can read more about it here
http://jinja.pocoo.org/docs/dev/templates/#assignments

--
Kai Stian Olstad

Willem D'Haese

unread,
Feb 24, 2018, 9:22:17 AM2/24/18
to ansible...@googlegroups.com
Jinja it is :)

Solved it with:

AllowUsers {% set ssh_allowusers = 'root' %}{% for x in dictusers %}{% set ssh_allowusers = ssh_allowusers ~ ' ' ~ x %}{% if loop.last %} {{ssh_allowusers }} {% endif %}{% endfor %}

Tx (again)

Willem D'Haese
Reply all
Reply to author
Forward
0 new messages