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

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

问题描述

我正在编写一个 Ansible 模板,需要生成主机组中的 ip 列表,排除当前主机 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天全站免登陆