Pushing items to a var while looping over another var in Ansible Jinja2 template

前端 未结 1 1627
忘了有多久
忘了有多久 2021-01-27 11:36

Inventory:

[Test]
local ansible_host=localhost

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

I\'m trying to write a jinja2 template iterating over m

1条回答
  •  醉梦人生
    2021-01-27 11:46

    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 ,.

    0 讨论(0)
提交回复
热议问题