Jinja2 For循环中的变量 [英] Variable in Jinja2 For Loop
问题描述
我们正在尝试提出一种在jinja2 For Loops中使用ansible事实的方法.
We're trying to come up with a way to use ansible facts within jinja2 For Loops.
例如,我想获取属于我的memcached组以及基于发行版(例如tag_release_dev
或tag_release_prod
之类)的组的所有服务器.当我尝试在For循环中使用{{ tt_release }}
时,它会评估{{ tt_release }}
而不是变量的值.有没有一种方法可以在循环定义中使用变量?
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 %}
推荐答案
它计算的是
{{ tt_release }}
而不是变量的值.
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.
您想要的是连接字符串"tag_release_"
和变量tt_release
.在Jinja2中,连接是用+
完成的.
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]) %}
这篇关于Jinja2 For循环中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!