Bootstrap FreeKB - Ansible - Gather facts using the setup module
Ansible - Gather facts using the setup module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

Facts are raw data about a system, such as the systems hostname and IP address. On your control node (that's your Ansible server), the ansible ad hoc command can be used to display facts about your Ansible server.

ansible localhost -m setup

 

Or you can use the ansible ad hoc command to gather facts for a target server.

ansible all --inventory server1.example.com, -m setup

 

For example, here are some facts.

"ansible_hostname": "server1"
"ansible_all_ip4v_addresses": "10.1.2.3"
"ansible_distribution": "CentOS"

 

By default, a playbook will gather facts. Here is a playbook that prints facts.

---
- hosts: all
  tasks:
    - debug:
        var: ansible_hostname
    - debug:
        var: ansible_all_ipv4_addresses
    - debug:
        var: ansible_distribution

 

Since facts are gathered by default, there is no need to use the setup module. However, you can include the setup module if you would like, as this could emphasize that facts are indeed being gathered. Gathering subset "all" is exactly the same as using the gather_facts module.

---
- hosts: all
  tasks:
    - name: Gather all facts
      setup:
        gather_subset:
          - all

    - debug:
        var: ansible_hostname
    - debug:
        var: ansible_all_ipv4_addresses
    - debug:
        var: ansible_distribution

 

Running the playbook will produce the following.

PLAY [all]

TASK [Gather all facts]
ok: [server1.example.com]

TASK [debug]
ok: [server1.example.com] => {
    "msg": "server1"
}

TASK [debug]
ok: [server1.example.com] => {
    "msg": "10.1.2.3"
}

TASK [debug]
ok: [server1.example.com] => {
    "msg": "CentOS"
}

PLAY RECAP
server1.example.com : ok=2  changed=0  unreacable=0  failed=0

 

Facts are often used with when to do something when a fact evaluates to true or false. For example.

- name: do something
  when: "ansible_distribution == 'CentOS'"

 

Often, the setup module is used when you need to only gather a subset of facts. In this example, only networking facts will be gathered, such as IP address.

---
- hosts: all
  tasks:
    - name: Gather only network facts
      setup:
        gather_subset:
          - '!all'
          - network

    - debug:
        var: ansible_all_ipv4_addresses
...

 

gather_subset accepts the following:

  • all
  • min
  • hardware
  • network
  • virtual
  • ohai
  • facter

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1ea640 in the box below so that we can be sure you are a human.