title: Ansible loop task with dynamic variable
body: <p>I would like set DNS Primary Addresses on hosts dynamicly with Ansible.
  The host group underneath should be extandable with X hosts and should still go on with this "dns entry loop" (see the list underneath).</p>
  
  <p>I have the following Servers in my Ansible inventory:</p>
  
  <pre><code>[yst-ad-server]
  server1
  server2
  server3
  </code></pre>
  
  <p>I want to set the DNS entrys for this servers like this:</p>
  
  <pre><code>Server:     Primary DNS:
  server1 --&gt; server3
  server2 --&gt; server1
  server3 --&gt; server2
  </code></pre>
  
  <hr>
  
  <p>Without loops my task is working and looks like this:</p>
  
  <pre><code>- name: Select all AD Servers (but the first in group) and set their DNS server to the first server in group (usually the master)
    win_dns_client:
      adapter_names: '*'
      ipv4_addresses: "{{ hostvars[groups[environment_name + '-ad-server'][-1]].ansible_host }}"
    when: inventory_hostname == groups[environment_name + '-ad-server'][0]
  </code></pre>
  
  <p>(Environment_Name is a var I set while running the playbook. In this case I would use "-e environemnt_name=yst" to match with the inventory group mentioned above.) <br>
  This part gets the IP of server3 (last in group, so I use -1) and set it on the first host (0) in group, which is server1 when the hostname of the current host matches.</p>
  
  <p>After some researches and tests, I am now at this point:</p>
  
  <pre><code>- name: name
    win_dns_client:
      adapter_names: '*'
      ipv4_addresses: "{{ hostvars[groups[environment_name + '-ad-server'][item]].ansible_host }}"
    when: inventory_hostname == groups[environment_name + '-ad-server'][item + 1]
    loop: "{{ range(-1, 3)|list }}"
  </code></pre>
  
  <p>Unfortunately this does not work.
  The error i get is: </p>
  
  <pre><code>The conditional check 'inventory_hostname == groups[environment_name + '-ad-server'][item + 1]' failed. The error was: error while evaluating conditional (inventory_hostname == groups[environment_name + '-ad-server'][item + 1]): list object has no element
  </code></pre>