Pushing items to a var while looping over another

2019-03-06 15:48发布

问题:

Inventory:

[Test]
local ansible_host=localhost

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

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 %}

which produces output:

A
B
C

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}}

回答1:

This can be achieved with assignments introduced in 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:

  • lack of set inside the expression,
  • using += operator,
  • not handling the last ,.