Stage 4 · Provision
Ansible Fundamentals
Gathering Facts
Setup module, custom facts, and conditional automation.
What Are Facts?
Facts are pieces of information Ansible gathers automatically about each managed node. They include OS details, IP addresses, hardware specs, installed packages, and more. Facts are available as variables in playbooks and templates.
The Setup Module
The setup module runs automatically at the start of every play, gathering facts from all hosts. You can run it manually or configure which subsets to collect.
# Gather all facts
ansible all -m setup
# Filter by subset
ansible all -m setup -a "filter=ansible_os_family"
# Gather only network facts
ansible all -m setup -a "filter=ansible_net*"Filtering facts reduces the amount of data collected and speeds up playbook execution, especially on large inventories.
Using Facts in Playbooks
- name: Configure based on OS
hosts: all
tasks:
- name: Install packages on Debian
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
- name: Install packages on RedHat
yum:
name: nginx
state: present
when: ansible_os_family == "RedHat"
- name: Show memory
debug:
msg: "Total RAM: {{ ansible_memtotal_mb }} MB"Facts make playbooks adaptive — one playbook works across different operating systems and hardware configurations.
Facts are the primary input for when conditionals. They let you write platform-agnostic playbooks that adapt to each host's environment automatically.
Custom Facts
Place custom fact files in /etc/ansible/facts.d/ on managed nodes. Ansible merges them into the ansible_facts namespace automatically.
[app]
version = 2.4.1
environment = production
tier = frontendCustom facts appear as ansible_facts.app.version. Use them for application-specific state that Ansible does not collect natively.
- name: Deploy based on app version
hosts: all
tasks:
- name: Show custom fact
debug:
msg: "App version: {{ ansible_facts.app.version }}"
- name: Deploy only to production
debug:
msg: "Deploying to production tier"
when: ansible_facts.app.environment == "production"Custom facts let you extend Ansible's knowledge with application-specific information stored on managed nodes.
Fact Caching
Fact caching stores gathered facts so subsequent playbook runs skip the gathering phase. This significantly speeds up repeated runs on large inventories.
[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts_cache
fact_caching_timeout = 3600gathering = smart skips fact gathering if cache is fresh. The cache timeout controls how long facts remain valid (in seconds).
If a playbook does not use facts, disable gathering with gather_facts: no. This skips the setup module and speeds up execution.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.