Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible loop task with dynamic variable

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

I have the following Servers in my Ansible inventory:

[yst-ad-server]
server1
server2
server3

I want to set the DNS entrys for this servers like this:

Server:     Primary DNS:
server1 --> server3
server2 --> server1
server3 --> server2

Without loops my task is working and looks like this:

- 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]

(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.)
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.

After some researches and tests, I am now at this point:

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

Unfortunately this does not work. The error i get is:

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
like image 603
k304 Avatar asked Aug 01 '26 16:08

k304


1 Answers

Your range has one too many positive elements: index 3 does not exist

Since you want to support X number of servers, rather than fixing the hardcoded value, create your range dynamically for the number of servers present in your group

range( -1, groups[environment_name + '-ad-server'] | length -1 ) | list

like image 138
Zeitounator Avatar answered Aug 04 '26 12:08

Zeitounator