Lesson 10 / 26

Facts About Hosts

Use gathered facts to adapt tasks to each host's operating system and hardware.

Ansible asks the host about itself

At the start of a play Ansible runs the setup module and collects facts such as ansible_os_family, ansible_distribution, memory, CPUs and network interfaces. You can use them in tasks and templates, for example to choose apt on Debian and dnf on Red Hat. Fact gathering takes a little time, so set gather_facts: false when you do not need them (as the example playbook does).

Asking one fact, run

I ran this on this machine; it is a Debian-family system.

ansible -i inventory.ini web1 -m ansible.builtin.setup -a "filter=ansible_os_family"

Output:

"ansible_os_family": "Debian",

Using a fact in a task

Choosing the right package manager from a fact keeps one playbook working on both families. (Illustrative; not run here.)

- name: Install nginx (Debian family)
  ansible.builtin.apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

- name: Install nginx (Red Hat family)
  ansible.builtin.dnf:
    name: nginx
    state: present
  when: ansible_os_family == "RedHat"

Quick check: Which module collects facts?

  • setup
  • ping
  • copy
  • debug
Answer

setup — The setup module gathers facts at the start of a play unless gather_facts is false.