【问题标题】:Ansible: Remove last comma in nested loop?Ansible:删除嵌套循环中的最后一个逗号?
【发布时间】:2020-06-06 09:00:31
【问题描述】:

我在 jinja2 模板中有以下内容。本质上,我正在遍历字典,选择名称,如果它不以“sh”开头,我将其添加到此配置中。但是,我想让服务器逗号分隔。

servers = {% for item in list_search_peers.json['entry'] %}{% if not item.name.startswith('sh-') %}{{ item.name }}{% endif %}{% endfor %}

通常我会这样做:

servers = {% for item in list_search_peers.json['entry'] %}{% if not item.name.startswith('sh-') %}{{ item.name }}{% if not loop.last %},{% endif %}{% endif %}{% endfor %}`

但是loop.last 不起作用,因为我正在过滤掉其中一个值。

我的输出是:

servers = x.x.x.x:8089,y.y.y.y:8089,

但我希望它没有最后一个,

servers = x.x.x.x:8089,y.y.y.y:8089

我正在尝试{% set } 设置一个变量,但没有运气。

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    首先过滤列表。例如

        - set_fact:
            my_list: "{{ list_search_peers.json.entry|
                         rejectattr('name', 'match', '^sh-(.*)$')|
                         list }}"
    

    然后在模板中使用它

    servers = {% for item in my_list %}{{ item.name }}{% if not loop.last %},{% endif %}{% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2018-02-14
      • 2020-01-24
      相关资源
      最近更新 更多