August 28, 2017 Gautier Franchini

Ansible – how to collect information about remote hosts with Gathers facts

 Anisble – how to collect information about your remote hosts

In order to do so, we will discuss about ansible modue: Gathers facts

:information_source: Official webpage:

Display facts from all hosts and store them at /tmp/facts indexed by hostname

ansible all -m setup --tree /tmp/facts

➡ now check the file to have a clear view off all variables (facts) collected by ansible for your host like the well known {{ inventory_hostname }}

To list the fact directly in your playbook you have to set gather_facts: True in your playbook

  gather_facts: True

    - debug: var=hostvars[inventory_hostname]['ansible_enp0s3']['ipv4']['address']

get current target host’s IP address and use it in your ansible role or playbook

You can use in your template.j2{{ ansible_eth0.ipv4.address }} the same way you use {{inventory_hostname}}

To set the value in your vars file

host_ip: "{{ ansible_enp0s3.ipv4.address }}"

use case

➡ here is an example:

I Hope it’ll help someone one day ッ



update: 2018-04-19

You can also use “setup” in your .yaml file.

e.g. In my current usecase, I need to get the default ipv4 addr:

- name: Gather facts from new server
    filter: ansible_default_ipv4.address

You can now call {{ ansible_default_ipv4.address }} in your playbook.
(setup load all the ansible_** variables)*

ℹ️ source: docs.ansible – setup_module


Tagged: ,

Contact Us