Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a particular host name's ip with ansible

I have a host file that looks roughly like this:

[kibanamaster]
efk host_ip host user passwd
[elasticnode]
esnode host_ip user passwd

and I am trying something in the style of

- name: get ip address node1
  debug: var=hostvars[inventory_host]['esnode']['ansible_default_ipv4']['address'] 
  register: es_node1

But I get variable not defined. Anyone outthere able to help?

EDIT: If I do

debug: var=hostvars[LOG1]['esnode']['ansible_default_ipv4']['address']
register: node_1 

I get

{"hostvars[LOG1]['ansible_default_ipv4']['address']": "VARIABLE IS NOT DEFINED!"}

like image 282
qubsup Avatar asked Jun 06 '17 12:06

qubsup


People also ask

How do I get a list of hosts in Ansible?

You can use the option --list-hosts. It will show all the host IPs from your inventory file. You can use the below-given command.

What is ansible_default_ipv4?

Most people think that ansible_default_ipv4 is some magical way to guess what IP address is the 'main' IP for a server. It is not. It is the IP address which resides on interface where the default route points to.


2 Answers

hostvars magic variable is a dictionary with keys named after hosts in your inventory.

So you may want to try:

hostvars['esnode']['ansible_default_ipv4']['address']

to get ip address of esnode host.

like image 64
Konstantin Suvorov Avatar answered Nov 04 '22 11:11

Konstantin Suvorov


You can use pre-loaded ansible variable to get values for both ipv4, ipv6 & hostname

IPV4 --> {{ ansible_eth0.ipv4.address }}

IPV6 --> {{ ansible_eth0.ipv6.address }}

Hostname --> {{ ansible_hostname }
like image 27
Kishore Venkataramanan Avatar answered Nov 04 '22 10:11

Kishore Venkataramanan