Jinja2 For 循环中的变量 [英] Variable in Jinja2 For Loop

查看:59
本文介绍了Jinja2 For 循环中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正试图想出一种在 jinja2 For 循环中使用可靠事实的方法.

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

例如,我想获取属于我的 memcached 组以及基于发布的组(类似于 tag_release_devtag_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 }} 而不是变量的值.

这是因为您已经在表达式中.你不能嵌套表达式 - 你也不需要.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆