What are facts in Ansible?
sobes.tech AI
Answer from AI
Facts in Ansible are variables that are automatically collected from target hosts when a playbook is executed. They contain information about the system, such as:
- Operating system and its version.
- IP addresses and network interfaces.
- Processor and memory information.
- Details about disk devices and filesystems.
- Other system characteristics.
Fact collection is performed by the setup module. By default, it runs at the beginning of each playbook unless disabled with the gather_facts: no option.
Facts are available in playbooks, roles, and templates as special variables with the prefix ansible_. For example:
---
# Output hostname of the target host
- name: Get system facts
hosts: all
tasks:
- name: Print hostname
debug:
msg: "Hostname: {{ ansible_hostname }}"
Using facts allows creating flexible and adaptive playbooks that can perform different actions depending on the configuration of target systems. For example, you can install different packages or apply different settings based on the operating system.
Fact collection can be disabled to improve playbook execution speed if this information is not needed:
---
# Disable fact collection
- name: Install Nginx without gathering facts
hosts: webservers
gather_facts: no # Disable fact gathering
tasks:
- name: Install nginx package
apt:
name: nginx
state: present
It is also possible to collect facts selectively to obtain only the necessary information and speed up the process:
---
# Gather only network facts
- name: Gather network facts only
hosts: all
gather_facts: smart # Smart fact gathering (caching)
tasks:
- name: Print IP address
debug:
msg: "IP Address: {{ ansible_facts['ipv4'] | map(attribute='address') | join(', ') }}" # Access to facts example
The setup module can be used to forcibly gather facts at any moment:
---
# Forcible fact gathering in the middle of a playbook
- name: Force facts gathering
hosts: database
tasks:
- name: Ensure dependencies are met
apt:
name: libpq-dev
state: present
- name: Gather facts explicitly
setup: # Forcible fact gathering
- name: Configure database
# Configuration logic using newly gathered facts
debug:
msg: "System memory total GB: {{ ansible_memory_mb['real']['total'] / 1024 | round(2) }}"
Understanding and effectively using facts is critical for writing powerful and scalable Ansible playbooks.