Get first “N” elements of a list in Jinja2 template in Ansible

北城以北 提交于 2020-01-03 19:19:43

问题


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

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 %}

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.

I thought of this:

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

...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?

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 %}?


回答1:


Simply:

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 %}


来源:https://stackoverflow.com/questions/46553820/get-first-n-elements-of-a-list-in-jinja2-template-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!