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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With