Search code examples
ansibletaskansible-2.xdelegation

Ansible - Delegate single task to a group of hosts where the inventory groupname contains a variable


I have an ansible task which runs on server1 (server is in group "yst-ad-server"). It should take the hosts IP address from hostvars and set it on server2 as DNS address. Server2 is in the group "yst-terminal-server". The part yst is dynamic, so it will be defined in a variable while running ansible ('-e "env=xxx"').

How can I use this to delegate it to server2? So far I got this but Ansible does not get the hosts, it says it cant connect to host "groups['yst-terminal-server']":

- name: name.
  win_dns_client:
    adapter_names: '*'
    ipv4_addresses: '{{ hostvars[inventory_hostname].ansible_host }}'
    where: inventory_hostname != groups['yst-ad-server'][-1]
  delegate_to: '{{ item }}'
  with_items: "groups['{{ env }}-terminal-server']"
  register: set_dns_ip

What I actually want would be like this:

with_items: '{{ groups.{{env}}-terminal-server }}'

Where env contains "yst". But this is not possible, because Ansible does not allow have a variable within a variable.



Edit:
I have already took a look at this link mentioned in comments but without any success yet:

- debug: msg="{{ (lookup('vars', env))-terminal-server }}"

Leads to the error:

The error was: No variable found with this name: yst

Solution

  • The solution is to look up the variable the following way:

    {{ groups[env + '-terminal-server' ] }}