Variable in Jinja2 For Loop

核能气质少年 提交于 2019-12-12 01:56:49

问题


We're trying to come up with a way to use ansible facts within jinja2 For Loops.

For example, I want to get all servers that belong to my memcached group as well as a group based on release (something like tag_release_dev or tag_release_prod). When I try to use {{ tt_release }} within the For Loop it evaluates {{ tt_release }} rather than the value of the variable. Is there a way to use a variable within the loop definition?

{% for host in groups["tag_function_mem"] | intersect(groups["tag_release_{{ tt_release }}"]) %}
  {{ host }}:11211
  {%- if not loop.last %},{% endif %}
  {%- if loop.last %}"{% endif %}
  {% endfor %}
{% endif %}

回答1:


it evaluates {{ tt_release }} rather than the value of the variable.

This is because you already are inside a expression. You can not nest expressions - and you don't need to.

What you want is to concatenate the string "tag_release_" and the variable tt_release. In Jinja2 concatenation is done with a +.

{% for host in groups["tag_function_mem"] | intersect(groups["tag_release_" + tt_release]) %}


来源:https://stackoverflow.com/questions/38212684/variable-in-jinja2-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!