Ansible – Get the IP address of another host from the hosts file

An example of how to get the IP address of another host from the "hosts" file by performing a task on another host.

 

  • server1our Playbook will be executed on it
  • server2we need its IP address in the Playbook

 

hosts:

[default]
server1 ansible_host=192.168.1.101
server2 ansible_host=192.168.1.102

 

In order to get the IP address, we will use "hostvars", where we indicate the name of the server we need, in our case it is "server2"

Playbook:

---
 
- name: example
  gather_facts: No
  hosts: server1
  
  tasks:
    - name: get-ip-from-server2
      debug:
        msg: "Server2 IP address is {{ hostvars[ 'server2' ].ansible_default_ipv4.address }}"

 

Output:

ok: [server1] => {
    "msg": "Server2 IP address is 192.168.1.102"
}
0 0 vote
Article Rating

Tagged: Tags

Подписаться
Уведомление о
guest
0 Comments
Inline Feedbacks
View all comments