Whenever we run an Ansible playbook, the first thing that happens is the “gather facts” task, its default task. Ansible uses Setup Module for gather facts. Ansible gathers live/current information about the remote system like Kernel & OS info, IP Address and Interface details, CPU/Memory/Disk space info etc.
# ansible servera -m setup
If we donot want to run “gather facts” task, we can disable Gathering Facts as below.
- hosts: whatever
Use this when we are not using any facts variables in our playbook as this will reduce execution time of our playbook
Manually collect fact
We you can collect facts at anytime in the playbook by just using setup module.
- name: Collect Facts
We can also create our own custom facts & these will be retrieved by Setup Module along with default facts. We can do this when -
- We want to get some facts or information that is not provided by Setup Module
- Using this we can set labels on Managed Node & use this labels to run a task on Node which have particular labels like tier=frontend, type=production using “when” conditions etc.
To create custom facts, on Managed Hosts we just have to create a directory at
/etc/ansible/facts.d. Inside this directory, we can place one or more
*.fact files. We can name them anything but they should have
We can also create
.fact file that contains a bash script. So when
"gather_facts" task is executed Ansible will run them and expect JSON on stdout.
Custom fact on Managed Node
- Create directory facts.d under /etc/ansible
- Create fact file
cat > myfact.fact
- When Ansible run the setup module, custom facts will be retrieved under ansible_local variable.
ansible all -m setup -a "filter=ansible_local"
- Use below playbook to run a task on Managed Node that has tag tier=frontend
- name: test for custom fact
- name: create file on server which has custom fact tier=frontend
content: "Test for Custom Modules"
when: ansible_local.myfact.myfact.tier == "frontend"
In this way we can create our custom facts & use them in playbook.