Facts are raw data about a system. On your control node (that's your Ansible server), the following command will display facts about your control node.
ansible localhost -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.
The ansible-doc setup command can be used to show the Ansible documention on the setup 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