在 Ansible Jinja2 模板中循环另一个变量时将项目推送到变量 [英] Pushing items to a var while looping over another var in Ansible Jinja2 template

查看:14
本文介绍了在 Ansible Jinja2 模板中循环另一个变量时将项目推送到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

库存:

[Test]
local ansible_host=localhost

[Test:vars]
my_clusters="A,B,C"

我正在尝试编写一个对 my_clusters 变量进行迭代的 jinja2 模板.在网络上,我主要发现以下迭代方式(也在这里 Ansible 模板中的 For 循环):

I'm trying to write a jinja2 template iterating over my_clusters var. Over the web mostly I found below way of iterating (Also here For loop in Ansible Template):

{% for item in hostvars[groups['Test'][0]]['my_clusters'].split(',') %}
{{item}}
{% endfor %}

产生输出:

A
B
C

但我的要求是打印字符串Cluster"(逗号分隔在同一行)与否相同的次数.my_clusters 变量中的项目.预期输出:

But my requirement is to print string "Cluster" (comma separated on the same line) as many times the no. of items in my_clusters var. Expected output:

Cluster,Cluster,Cluster

我尝试过类似下面的方法.但它不起作用.

I tried something like below. But it's not working.

{% set str="" %}
{% for cluster in hostvars[groups['Test'][0]]['my_clusters'].split(',') %}
{% str += "Cluster," %}
{% endfor %}
{{str}}

推荐答案

这可以通过 Jinja2 2.10 中引入的赋值:

{% set ns = namespace(str="") %}
{% for cluster in hostvars[groups['Test'][0]]['my_clusters'].split(',') %}
{% set ns.str = ns.str + "Cluster" %}
{%- if not loop.last %}{% set ns.str = ns.str + "," %}{% endif %}
{% endfor %}

<小时>

以上回答了标题中的问题,但您的代码存在一些语法问题:


The above answers the question from the title, but there are some syntactical problems with your code:

  • 表达式中缺少set
  • 使用 += 运算符,
  • 不处理最后一个,.
  • lack of set inside the expression,
  • using += operator,
  • not handling the last ,.

这篇关于在 Ansible Jinja2 模板中循环另一个变量时将项目推送到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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