# ansible / foundations / facts
Context-Aware Automation with Ansible Facts
Ansible Facts are variables automatically collected from your managed nodes before tasks are executed. They provide deep system insights—from IP addresses to CPU details—allowing your playbooks to adapt dynamically to the environment.
What are Ansible Facts?
Instead of hardcoding a server's IP address or manually checking if a server is RedHat or Ubuntu, Ansible queries the target host and builds a massive dictionary of variables called Facts.
Why are they important?
Facts make automation context-aware. You can write highly reusable playbooks that behave differently based on the system they are running against. For example: "If OS is Debian, use apt; if RedHat, use yum."
What data is collected?
Ansible collects hardware architecture, active IP addresses, hostname, total memory, disk space, network interfaces, and much more.
The Gathering Phase
The Execution Flow
- 1. Connect
Ansible connects to the remote server via SSH (or WinRM).
- 2. Gather
Ansible automatically runs the
setupmodule behind the scenes to collect all system facts. - 3. Execute
Ansible runs your defined tasks, substituting any fact variables (like
{{ ansible_hostname }}) with the collected data.
--- - hosts: web gather_facts: no tasks: - name: Install nginx apt: name: nginx state: present
Does gathering facts take time? Yes. If you have hundreds of servers and your playbook doesn't rely on system variables, use gather_facts: no to speed up execution significantly.
Commands & Common Facts
You don't have to guess what facts are available. You can run an ad-hoc command using the setup module to dump the entire JSON payload of facts for any server.
| Fact Variable (Jinja2) | Description |
|---|---|
{{ ansible_hostname }} | The short hostname of the target server. |
{{ ansible_os_family }} | The OS family group (e.g., Debian, RedHat, Windows). |
{{ ansible_default_ipv4.address }} | The active, default IPv4 address of the server. |
{{ ansible_processor }} | Detailed information about the CPU architecture and cores. |
{{ ansible_memtotal_mb }} | The total physical RAM available on the machine (in MB). |
Quick Recap
Ansible Facts are automatically collected variables containing deep system information.
Facts are gathered seamlessly at the start of a playbook run, right before the first task executes.
Disable them using gather_facts: no in your playbook, or explore them manually via the terminal using ansible all -m setup.