Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first "N" elements of a list in Jinja2 template in Ansible

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

like image 856
dan_linder Avatar asked Oct 03 '17 21:10

dan_linder


People also ask

Does Ansible use Jinja2 template?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

Why is Jinja2 used in Ansible?

Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.


1 Answers

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 %}
like image 55
techraf Avatar answered Nov 09 '22 03:11

techraf