如何删除或排除Ansible模板列表中的项目? [英] How to remove or exclude an item in an Ansible template list?

查看:315
本文介绍了如何删除或排除Ansible模板列表中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Ansible模板,该模板需要在主机组中生成IP列表, 不包括 。我已经在网上和文档中进行了搜索,但是找不到任何允许您删除列表中项目的过滤器。我在下面创建了(hacky)for循环来执行此操作,但我想知道是否有人知道这样的最佳实践过滤方法。

I'm writing an Ansible template that needs to produce a list of ip's in a host group, excluding the current hosts IP. I've searched around online and through the documentation but I could not find any filters that allow you to remove an item in a list. I have created the (hacky) for loop below to do this but was wondering if anyone knew a "best practice" way of filtering like this.

{% set filtered_list = [] %}

{% for host in groups['my_group'] if host != ansible_host %}
    {{ filtered_list.append(host)}}
{% endfor %}

可以说groups ['my_group']有3 ip(192.168.1.1、192.168.1.2和192.168.1.3)。当为192.168.1.1生成模板时,应该只打印IP的192.168.1.2和192.168.1.3。

Lets say groups['my_group'] has 3 ip's (192.168.1.1, 192.168.1.2 and 192.168.1.3). When the template is generated for 192.168.1.1 it should only print the ip's 192.168.1.2 and 192.168.1.3.

推荐答案

差异 过滤器为此:

- debug: var=item
  with_items: "{{ groups['my_group'] | difference([inventory_hostname]) }}"

这将为您提供 my_group 没有当前主机。

This will give you all items hosts from my_group without current host.

这篇关于如何删除或排除Ansible模板列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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