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

查看:313
本文介绍了获得第一个“ 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循环,还是需要将三个名称服务器行包装在 {%中,如果(dns4_ips | shuffle(seed = inventory_hostname))[1]已定义%}

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天全站免登陆