Ansible Automation

Context-Aware Automation with Ansible Facts

Lesson 7 of 12 · 7 min · Intermediate

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 setup module 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.
Disabling Facts for Speed
---
- hosts: web
  gather_facts: no
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present

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.

terminal

# Manually view all collected facts from managed nodes
$ ansible all -m setup
server-01 | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "x86_64",
        "ansible_hostname": "server-01",
        ...
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