ansible - variables reuse in templates

242 views
Skip to first unread message

Pavlo Zhuk

unread,
Oct 19, 2015, 10:17:24 AM10/19/15
to Ansible Project
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

Matt Martz

unread,
Oct 19, 2015, 10:22:30 AM10/19/15
to ansible...@googlegroups.com
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

--
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 ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/1c36130f-f6b7-4a4f-abf7-3c3a1a26aba3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Matt Martz
@sivel
sivel.net
Reply all
Reply to author
Forward
0 new messages