Jinja2 has some unexpected variable scopes when it comes to loops.  You are
setting mynewvar inside of a scope for a for loop, which is not available
outside of the for loop.

There is some explanation at a similar issue logged on the jinja2 project:
https://github.com/mitsuhiko/jinja2/issues/330

On Mon, Oct 19, 2015 at 9:14 AM, Pavlo Zhuk <[email protected]> wrote:

> Dears,
>
> I am trying to construct a variable inside the loop of ansible template.
> The value gets constructed, but  I'm unable to use it outside the loop.
> Looks like variables with same name inside the loop and outside the loop
> are pointing to actually different variables.
>
> Is there any way to construct a varialbe inside the loop, and use it
> outside?
>
> Example playbook:
>
> ---
> - hosts: "localhost"
>  connection: local
>  gather_facts: False
>
>  vars:
>    test_list:
>      - foo
>      - bar
>      - gotcha
>
>  tasks:
>     - name: templating test
>       template: src=dynvars.j2 dest=/tmp/testvars.txt
>
>
>
> dynvars.j2 template:
>
>
>
>                                   [0/0]
> {% set mynewvar = "test" %}
> {% for value in test_list %}
>  {% set mynewvar = value %}
> {{ mynewvar }}
>
> {% endfor %}
>
> {{ mynewvar }}
>
>
>
> Actual result:
>
> Inside: foo
> Inside: bar
> Inside: gotcha
>
> Outside:test     <------- Here I would expect 'gotcha' as it was last one
> assigned inside the loop
>
>
>
> Any responses appreciated!
>
> Thanks
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/1c36130f-f6b7-4a4f-abf7-3c3a1a26aba3%40googlegroups.com
> <https://groups.google.com/d/msgid/ansible-project/1c36130f-f6b7-4a4f-abf7-3c3a1a26aba3%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Matt Martz
@sivel
sivel.net

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/CAD8N0v9x4tn0Zn_9vYSWRRO1Udn3zkhszANtweT32T3LmAUcuA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to