TExcelTAD
Home › Configuration Management: Ansible › Facts & set_fact

Facts & set_fact

Facts are what Ansible learns about a host at the start of a play: OS and version, CPU count, memory, network interfaces and addresses, mounts, the Python in use, environment variables. The setup module collects them, and every play with gather_facts: true (the default) runs it first, as the hidden task Gathering Facts.

Facts let one playbook adapt: install with apt on Debian and dnf on Red Hat, size worker pools by CPU count, bind a service to the host's private IP.

Looking at facts

Facts live in ansible_facts (dictionary keys without the ansible_ prefix). Many values differ from machine to machine; this session prints only ones that are fixed for the sandbox:

bash · try it yourself
cat > facts.yml <<'YML'
- name: Facts
  hosts: localhost
  gather_facts: true
  tasks:
    - name: A few stable facts
      ansible.builtin.debug:
        msg:
          - "system: {{ ansible_facts['system'] }}"
          - "os family: {{ ansible_facts['os_family'] }}"
          - "distribution: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }} ({{ ansible_facts['distribution_release'] }})"
          - "hostname: {{ ansible_facts['hostname'] }}"
          - "user: {{ ansible_facts['user_id'] }}"
          - "package manager: {{ ansible_facts['pkg_mgr'] }}"
          - "service manager: {{ ansible_facts['service_mgr'] }}"
YML
ansible-playbook facts.yml | sed -n '/"msg"/,/^    ]/p'
    "msg": [
        "system: Linux",
        "os family: Debian",
        "distribution: Ubuntu 24.04 (noble)",
        "hostname: tad",
        "user: learner",
        "package manager: apt",
        "service manager: sysvinit"
    ]

service_mgr is not systemd here, because the sandbox container doesn't boot systemd; on a real Ubuntu server it would be. Facts tell the truth about the machine you are on.

Ad hoc, filter the setup output: ansible web1 -m ansible.builtin.setup -a 'filter=ansible_distribution*', or -a 'gather_subset=!all,network' to gather less.

Note: You will also see the older top-level form ansible_distribution. It is the same value, injected as a variable for every fact. The setting inject_facts_as_vars controls this; prefer ansible_facts['distribution'], which is unambiguous and survives if the injection is switched off.

Using facts for decisions

yaml
- name: Install the web server (Debian family)
  ansible.builtin.apt:
    name: nginx
  when: ansible_facts['os_family'] == "Debian"

- name: Install the web server (Red Hat family)
  ansible.builtin.dnf:
    name: nginx
  when: ansible_facts['os_family'] == "RedHat"

- name: Worker count from the CPU count
  ansible.builtin.set_fact:
    app_workers: "{{ ansible_facts['processor_vcpus'] * 2 }}"

(For packages, ansible.builtin.package picks the right manager by itself when the package name is the same everywhere.)

Speed: don't gather what you don't use

Gathering takes about a second per host and a lot more on hosts with many mounts or interfaces. Options:

Option Effect
gather_facts: false skip it for plays that don't use facts (most examples in this course)
gather_subset: [network, hardware] collect only some groups
fact caching (fact_caching = jsonfile in ansible.cfg) reuse facts between runs for fact_caching_timeout seconds; also lets play 2 use facts of hosts it doesn't target

set_fact: your own variables during the run

set_fact computes a variable for the current host, from facts, registered results or other variables. It has a high precedence (only -e and role/include parameters beat it):

bash · try it yourself
cat > setfact.yml <<'YML'
- name: Computed variables
  hosts: localhost
  gather_facts: false
  vars:
    app_env: staging
    base_port: 8000
  tasks:
    - name: Derive settings
      ansible.builtin.set_fact:
        app_port: "{{ base_port + (100 if app_env == 'prod' else 10) }}"
        app_url: "https://{{ app_env }}.example.com"

    - name: Show
      ansible.builtin.debug:
        msg: "{{ app_url }} on port {{ app_port }} ({{ app_port | type_debug }})"
YML
ansible-playbook setfact.yml | grep msg
    "msg": "https://staging.example.com on port 8010 (int)"

The result of "{{ … }}" is converted back to a native type when it looks like one: 8010 became an int.

Custom facts

A server can describe itself: executable or INI/JSON files in /etc/ansible/facts.d/*.fact appear under ansible_facts['ansible_local']. A role can drop /etc/ansible/facts.d/linkly.fact with {"version": "2.4.1"}, and later plays read ansible_facts['ansible_local']['linkly']['version'] to decide whether to upgrade.

Test yourself

Where are facts stored for use in templates and conditions?

  1. hostvars['facts']
  2. ansible_facts
  3. facts.d
  4. setup_result

A play never uses facts. What should it set?

  1. gather_facts: false
  2. facts: none
  3. setup: skip
  4. Nothing, facts are free

Which module installs packages with whichever manager the host uses?

  1. ansible.builtin.package
  2. ansible.builtin.apt
  3. ansible.builtin.command
  4. ansible.builtin.setup