Variables, facts & precedence
Where values come from and who wins.
Variables let one playbook adapt to many hosts and environments. They come from many places — inventory (group_vars, host_vars), the playbook, roles, extra-vars on the command line, and facts gathered from the hosts. The power and the pitfall are the same: with so many sources, you must know the precedence order, because when two define the same variable, the higher-precedence one silently wins.
# variables for every host in the web groupnginx_worker_processes: 4app_port: 8080---# host_vars/web1.acme.internal.yml — overrides for one hostapp_port: 8081
Facts
Facts are variables Ansible discovers about each host at run time — OS family, IP addresses, memory, mounted disks — gathered automatically at the start of a play (or on demand with the setup module). You use them to write portable automation: install apt packages on Debian and dnf on RHEL by branching on ansible_facts[‘os_family’], size a config from the host’s real memory, and so on.
$ ansible web1 -i inventory.ini -m setup -a "filter=ansible_os_family"web1 | SUCCESS => { "ansible_facts": { "ansible_os_family": "Debian" } }# use it in a task: when: ansible_facts['os_family'] == "Debian"