What are Ansible facts, and how do they get into a play?
Facts are variables Ansible collects automatically from each managed host: hostname, kernel version, network interfaces and IP addresses, OS version, CPU count, memory, disks and free space. Before the first task of each play, the ansible.builtin.setup module runs and gathers them; the output shows this as the "Gathering Facts" task.
Facts let a play react to the actual state of each machine instead of assuming it. Examples:
- restart a server only if a fact shows a certain service is in a certain state
- size a MySQL buffer from the memory a fact reports
- write the host's own IPv4 address into a configuration file
You don't add a task for this; gathering happens implicitly at the start of every play, unless you turn it off. In Ansible 2.3 and later the output labels it TASK [Gathering Facts]; older versions showed setup.
You can also define custom facts stored on the host itself, for values that are specific to that system.
Go deeper:
Ansible facts (official docs) — what is collected and how to use it.
ansible.builtin.setup module (official docs) — the module that does the gathering.