get a particular host name's ip with ansible
Asked Answered
G

2

7

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

Galliwasp answered 6/6, 2017 at 12:10 Comment(0)
A
3

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 }
Astrobiology answered 24/8, 2018 at 15:52 Comment(1)
Of course, this will only work if you have an eth0.Essie
E
8

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.

Ento answered 6/6, 2017 at 12:37 Comment(4)
OK I take it back - it does not work - hostvars[LOG1]['ansible_default_ipv4']['address']": "VARIABLE IS NOT DEFINED!"Galliwasp
What is LOG1 here?Ento
LOG1 is a machine, but the point is that the moment i register that variable - I get an ugli long text in the configuration file I have rather than just the IP.Galliwasp
Ensure that LOG1 is defined, and facts has been gathered for this host before the point in time when you try to fetch ip address from hostvars.Ento
A
3

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 }
Astrobiology answered 24/8, 2018 at 15:52 Comment(1)
Of course, this will only work if you have an eth0.Essie

© 2022 - 2024 — McMap. All rights reserved.