Introduction to AnsibleANSIBLE Course Material · Practical Exercises · BONUS
BONUS · Adaptive Ansible Playbooks

Understanding and Using gather_facts

This practical bonus shows how Ansible discovers facts about managed machines, how to use them in real decisions, and how to gather only the facts you need. The exercises work with the existing inventory.ini lab.

Learning objectives: understand automatic fact gathering, distinguish facts from magic variables, inspect facts, make conditional decisions and collect facts explicitly.

1. What are facts?

Facts are data collected from a managed host, such as its Linux distribution, hostname, memory, architecture and network interfaces. At the start of a play, Ansible normally runs its fact-gathering mechanism (using ansible.builtin.setup for standard system facts).

gather_facts: true   # Default for a play (unless configured otherwise)
gather_facts: false  # Skip automatic collection
Important distinction: inventory_hostname is an Ansible magic variable and is available even with gather_facts: false. ansible_facts['hostname'] comes from the remote machine and must first be collected (or already be available through a facts cache).

2. First demonstration: display the facts

On the control node, create facts.yml in ~/ansible-lab:

---
- name: Discover our managed hosts
  hosts: all
  gather_facts: true

  tasks:
    - name: Show host information
      ansible.builtin.debug:
        msg:
          - "Inventory name: {{ inventory_hostname }}"
          - "System hostname: {{ ansible_facts['hostname'] }}"
          - "Distribution: {{ ansible_facts['distribution'] }}"
          - "Version: {{ ansible_facts['distribution_version'] }}"
          - "Architecture: {{ ansible_facts['architecture'] }}"
          - "RAM: {{ ansible_facts['memtotal_mb'] }} MB"
ansible-playbook -i inventory.ini facts.yml

Notice the initial TASK [Gathering Facts]. The following debug task displays values specific to each host. The inventory name and system hostname may differ.

3. Experiment: disable fact gathering

Change the play to gather_facts: false and run it again. In a normal lab without persistent fact caching, the task fails when it tries to access ansible_facts['hostname']. However, inventory_hostname still works.

---
- name: Compare an inventory variable with facts
  hosts: all
  gather_facts: false

  tasks:
    - name: This works without facts
      ansible.builtin.debug:
        msg: "Inventory host: {{ inventory_hostname }}"

    - name: This needs collected facts
      ansible.builtin.debug:
        msg: "System host: {{ ansible_facts['hostname'] }}"
Note: If fact caching has been enabled, previously collected facts may still be available. For a clear demonstration, use an inventory without persistent fact caching.

4. Advanced demonstration: adapt tasks to each operating system

A useful application is to run different tasks according to the Linux distribution family. This playbook installs the appropriate Apache package on Debian-based or Red Hat-based hosts. Run it only on your lab VMs.

---
- name: Install Apache according to the OS family
  hosts: all
  become: true
  gather_facts: true

  tasks:
    - name: Install Apache on Debian-based systems
      ansible.builtin.apt:
        name: apache2
        state: present
        update_cache: true
      when: ansible_facts['os_family'] == 'Debian'

    - name: Install Apache on Red Hat-based systems
      ansible.builtin.dnf:
        name: httpd
        state: present
      when: ansible_facts['os_family'] == 'RedHat'

    - name: Explain the selected OS family
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} belongs to {{ ansible_facts['os_family'] }}"

What to observe: Ansible evaluates when separately for each host. On Debian, the DNF task is skipped; on a Red Hat-family system, the APT task is skipped. This is how one playbook can adapt to several environments.

5. Advanced demonstration: make a decision based on RAM

Facts are not limited to displaying information. Here, Ansible checks the available physical RAM and chooses a configuration value. The example does not modify the system: it safely demonstrates a real configuration decision.

---
- name: Choose a configuration according to memory
  hosts: all
  gather_facts: true

  tasks:
    - name: Choose the number of application workers
      ansible.builtin.set_fact:
        app_workers: "{{ 4 if ansible_facts['memtotal_mb'] | int >= 2048 else 1 }}"

    - name: Explain the decision
      ansible.builtin.debug:
        msg:
          - "Host: {{ inventory_hostname }}"
          - "RAM: {{ ansible_facts['memtotal_mb'] }} MB"
          - "Selected workers: {{ app_workers }}"

    - name: Warn when the machine has less than 2 GB RAM
      ansible.builtin.debug:
        msg: "WARNING: low-memory host; use a lightweight configuration."
      when: ansible_facts['memtotal_mb'] | int < 2048

Why this matters: set_fact creates a host-specific variable during execution. The Jinja expression selects four workers for hosts with at least 2048 MB RAM, otherwise one. The final task runs only on low-memory machines. This pattern can be reused for templates, services or application settings.

6. Collect facts manually, only when required

Automatic collection can be disabled and performed later using ansible.builtin.setup. The filter parameter reduces the returned fact data; it is especially useful when you only need one category of facts.

---
- name: Collect memory information on demand
  hosts: all
  gather_facts: false

  tasks:
    - name: Start without collected facts
      ansible.builtin.debug:
        msg: "Starting on {{ inventory_hostname }}"

    - name: Gather only memory-related facts
      ansible.builtin.setup:
        filter:
          - ansible_memtotal_mb

    - name: Use the collected memory value
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} has {{ ansible_facts['memtotal_mb'] }} MB RAM"
Technical note: setup with filter limits which facts are returned, but it does not necessarily avoid every underlying system probe. Use gather_subset as well when you need finer control over collection.

7. Useful facts and variables

ExpressionMeaningRequires fact gathering?
inventory_hostnameHost alias in inventoryNo
ansible_facts['hostname']Remote system hostnameYes
ansible_facts['os_family']Operating system familyYes
ansible_facts['distribution']Linux distributionYes
ansible_facts['architecture']Processor architectureYes
ansible_facts['memtotal_mb']Total physical RAM in MBYes
group_namesInventory groups for the hostNo

8. Practical challenge

  1. Run the first playbook on at least two hosts and compare their results.
  2. Disable automatic gathering and explain which variable remains available.
  3. Write a task that displays "LOW MEMORY" when RAM is below 2048 MB and "ENOUGH MEMORY" otherwise.
  4. Bonus: use ansible.builtin.setup to collect facts only after the first task.
Suggested solution for the memory challenge
- name: Display memory assessment
  ansible.builtin.debug:
    msg: "{{ 'LOW MEMORY' if ansible_facts['memtotal_mb'] | int < 2048 else 'ENOUGH MEMORY' }}"

9. Knowledge check

1) What does gather_facts: false do?
  • A. Disables all variables
  • B. Skips automatic fact gathering
  • C. Prevents SSH connections
2) Which variable works without collected system facts?
  • A. inventory_hostname
  • B. ansible_facts['memtotal_mb']
  • C. ansible_facts['distribution']
3) Which module gathers facts explicitly?
  • A. ansible.builtin.debug
  • B. ansible.builtin.setup
  • C. ansible.builtin.copy
Answer key
1) B · 2) A · 3) B
Key takeaway: facts turn static playbooks into adaptive automation. Collect the information you need, then use when, set_fact and templates to make host-specific decisions.