Using Ansible Facts
# Using Ansible Facts
Ansible Facts are valuable data returned by Ansible from its target nodes when it runs a playbook. It gives us detailed information about the system or node. This data can be used to configure the system based on its current state.
## Gathering Facts
By default, Ansible automatically runs the setup module before executing tasks in a playbook. This setup module is responsible for gathering facts about the system.
```yaml
---
- hosts: all
tasks:
- name: Display all facts
debug:
var: ansible_facts
The above playbook will display all the facts gathered from the target node.
Using Facts
Once the facts are gathered, we can use them in our playbook. For example, let's use the ansible_distribution
fact that contains the name of the OS distribution.
---
- hosts: all
tasks:
- name: Check if the OS is Ubuntu
debug:
msg: "This is an Ubuntu system"
when: ansible_facts['os_family'] == "Debian"
In this playbook, the debug message will only be displayed if the operating system is a Debian-based one, like Ubuntu.
Disabling Fact Gathering
There are scenarios where we might not want to gather facts. We can disable the fact gathering by setting gather_facts
to no.
---
- hosts: all
gather_facts: no
tasks:
- name: This will not gather facts
debug:
msg: "Facts are not gathered"
Custom facts
Ansible allows you to deal with custom facts. These are facts you define for your hosts, not gathered by Ansible. For example, you can set a fact for the application version.
---
- hosts: all
tasks:
- name: Set custom fact
set_fact:
app_version: "1.0.0"
Then, you can use this fact in later tasks or templates.
Facts Caching
Caching facts can be beneficial when dealing with large inventories or complicated playbooks. To enable fact caching, add the following to ansible.cfg:
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_fact_cache
fact_caching_timeout = 86400
After setting this, Ansible will store gathered facts in JSON files in the directory specified by fact_caching_connection
for the time specified by fact_caching_timeout
.
In conclusion, Ansible Facts are a powerful tool that allows you to tailor your configuration management to the state of your systems. They can be used out of the box, disabled, and even customized to suit your needs.