获得第一个“N"Ansible 中 Jinja2 模板中列表的元素 [英] Get first "N" elements of a list in Jinja2 template in Ansible

查看:21
本文介绍了获得第一个“N"Ansible 中 Jinja2 模板中列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的大多数位置都有 4 个以上的 DNS 源,但有一些位置较少.每个位置都有自己的 dns4_ips 列表变量,如下所示:

Most of my locations have 4+ DNS sources, but a few have less. Each location gets their own dns4_ips list variable like this:

dns4_ips:
  - dns_A
  - dns_B
  - dns_C
  - dns_C

我的 resolv.conf 模板如下所示:

My resolv.conf template looks like this:

domain example.com
search example.com dom2.example.com dom3.example.com
{% for nameserver in (dns4_ips|shuffle(seed=inventory_hostname)) %}
nameserver {{nameserver}}
{% endfor %}

Jinja for 循环效果很好,但在我有很多名称服务器的情况下,我宁愿只列出 shuffle() 返回的前 3 个.

The Jinja for loop works great, but in the cases where I have numerous nameservers I'd rather only list the first 3 that the shuffle() returns.

我想到了这个:

nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[0] }}
nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[1] }}
nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[2] }}

...但在某些情况下,我只有一个或两个可用的 DNS 服务器,因此它们会产生不正确的行或错误,对吗?

...but there are some cases where I only have one or two DNS servers available so those would produce either an incorrect line or an error, correct?

是否有一种干净的方法可以使用 for 循环来处理这个问题,或者我是否需要将三个名称服务器行包装在 {% if (dns4_ips|shuffle(seed=inventory_hostname))[1] is defined %}?

Is there a clean way to handle this with the for loop, or do I need to wrap the three nameserver lines in {% if (dns4_ips|shuffle(seed=inventory_hostname))[1] is defined %}?

推荐答案

简单:

domain example.com
search example.com dom2.example.com dom3.example.com
{% for nameserver in (dns4_ips|shuffle(seed=inventory_hostname))[:3] %}
nameserver {{nameserver}}
{% endfor %}

这篇关于获得第一个“N"Ansible 中 Jinja2 模板中列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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