Ansible - access var of another host

210 Views Asked by At

I have this piece of the playbook.

- hosts: iperf_servers
  remote_user: root
  tasks:
  - name: print server iperf
    debug: msg="Starting Server Iperf with Data_IP > {{ hostvars[inventory_hostname].nodes[0].data_ip }}"
  - name: start server iperf
    shell: "iperf3 -B {{ hostvars[inventory_hostname].nodes[0].data_ip }} --server --one-off --daemon"
  - name: print friendly output
    debug: msg="Started Server IPERF On ip > {{ hostvars[inventory_hostname].nodes[0].data_ip }}"

- hosts: iperf_clients
  remote_user: root
  tasks: 
  - name: print iperf server data_ip's from client
    debug: var="{ hostvars['groups']['iperf_servers'][0].data_ip }}"

In the first play, with hosts 'iperf_servers' I'm accessing the var 'data_ip', which is stored inside host_vars, and this is how it looks:

---
name: server00
nodes:
-   instanceID: 0
    data_ip: 200.100.1.150

#** Note: under host_vars directory, I have 3 server files: **#

'ls  light-app/ansible/inventories/cluster_example/host_vars/'

server00.yml  server01.yml  server02.yml

As can be noticed, I'm accessing this var by:

{{ hostvars[inventory_hostname].nodes[0].data_ip }}

and it works just fine, I'm getting the value I'm expecting (the data_ip value) for each server file.

What I need in the second play, is to access the same var, but while I'm running it on other hosts groups (iperf_clients). The idea is to get the data_ip of the servers and set it on the clients. So basically I'm trying to use the data_ip of another host.

This way didn't work:

{{ hostvars['groups']['iperf_servers'][0].data_ip }}

I have tried so many ways and searched for so long. Is there a possible way to get these vars?

1

There are 1 best solutions below

5
Rickkwa On

Did you mean to do the following?

{{ hostvars[groups['iperf_servers'][0]].nodes[0].data_ip }}

In ansible, groups is a special variable -- a dictionary where key is the name of a host group, and value is a list of the servers in that host group.

Doing hostvars['groups'] means it is looking for a server named "group" in your inventory which likely doesn't exist. So instead, groups['iperf_servers'] will access the dictionary and return a list of hostnames for all your iperf servers.

Edit:

To get IPs from all iperf_servers

{{ groups['iperf_servers'] | map('extract', hostvars, 'nodes') | map('first') | map(attribute='data_ip') | list }}

Check the docs for the map extract if you're interested.