Ansible custom facts

Ansible Facts

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

Disable facts

If we donot want to run “gather facts” task, we can disable Gathering Facts as below.

- hosts: whatever
gather_facts: no

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.

tasks:
- name: Collect Facts
setup:

Custom 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 .fact extension

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
mkdir /etc/ansible/facts.d
  • Create fact file
cd /etc/ansible/facts.d 
cat > myfact.fact
[myfact]
tier=frontend
type=production

[application]
db=msql
  • 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
hosts: dev
tasks:
- name: create file on server which has custom fact tier=frontend
copy:
content: "Test for Custom Modules"
dest: /root/custom_file
when: ansible_local.myfact.myfact.tier == "frontend"

In this way we can create our custom facts & use them in playbook.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store