title: Get first "N" elements of a list in Jinja2 template in Ansible
body: <p>Most of my locations have 4+ DNS sources, but a few have less.  Each location gets their own <code>dns4_ips</code> list variable like this:</p>
  
  <pre><code>dns4_ips:
    - dns_A
    - dns_B
    - dns_C
    - dns_C
  </code></pre>
  
  <p>My resolv.conf template looks like this:</p>
  
  <pre><code>domain example.com
  search example.com dom2.example.com dom3.example.com
  {% for nameserver in (dns4_ips|shuffle(seed=inventory_hostname)) %}
  nameserver {{nameserver}}
  {% endfor %}
  </code></pre>
  
  <p>The Jinja <code>for</code> loop works great, but in the cases where I have numerous nameservers I'd rather only list the first 3 that the <code>shuffle()</code> returns.</p>
  
  <p>I thought of this:</p>
  
  <pre><code>nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[0] }}
  nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[1] }}
  nameserver {{ (dns4_ips|shuffle(seed=inventory_hostname))[2] }}
  </code></pre>
  
  <p>...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?</p>
  
  <p>Is there a clean way to handle this with the for loop, or do I need to wrap the three nameserver lines in <code>{% if (dns4_ips|shuffle(seed=inventory_hostname))[1] is defined %}</code>?</p>