Ansible Custom Facts
Ansible is an open source IT automation engine that automates provisioning, configuration management, application deployment, orchestration, and many other IT processes.
In Layman term, Ansible is a configuration management tool that can configure numbers of machine at a time regardless of their distribution families such as RedHat, Debian, Arch and so on.
let’s say I have to install nginx on 100s of machine and machines are of different type such as Rocky Linux, Ubuntu, FreeBSD, Manjaro and so on. Now to install, all I have to run this:
ansible nginx_target_hosts -m service -a "name=nginx state=started"
or
- hosts: nginx_target_hosts
tasks:
- name: install nginx
service:
name: nginx
state: started
Wait wait wait! Different distribution has different type of package manager but how a single task is able to install on all of them??? In the above image there is a task called “Gathering Facts” which is not introduced by us in our YAML file. So what are Facts ?
FACTS
Facts are the different type of information about the target node which include hardware, network, O.S., Python, host name and so on. To check
ansible localhost -m setup
CUSTOM FACTS
While I was working on task where I had to configure around 600 machine and while doing that I ran into an issue, that is
- Every machine had a specific file containing numbers of variables that serves as inventory to ansible. Variables value can be different for different machines which stopped me to configure the machine remotely.
- Organisation didn’t want to change it.
- That’s where I got a chance to create our own facts.
Let me give you a beautiful example:
Image 3, these are the variables I wanted to add into facts. Here’s the file from which I got this
How to do it?
There are two ways: First
- Updated Ansible core python scripts → https://github.com/navsin189/ansible_custom_facts?tab=readme-ov-file#changes-for-custom-facts
- I have created lib/ansible/module_utils/facts/other/personal.py
- then updated lib/ansible/module_utils/facts/default_collectors.py
- But here’s the catch → “I don’t like this method”.
Second and the easiest one:
In your target or managed nodes
sudo mkdir -p /etc/ansible/facts.d
sudo touch /etc/ansible/facts.d/myfacts.fact
-- Via Ansible
ansible target_host_group -m file -a "path=/etc/ansible/facts.d state=directory become=root"
ansible target_host_group -m file -a "path=/etc/ansible/facts.d/myfacts.fact state=touch become=root"
Here’s mine
By default ansible search for custom facts under /etc/ansible/facts.d/*.fact
but it can be changed under ansible.cfg
by mentioning fact_path=your_path
under [defaults]
So, create your own facts and enjoy.
Thanks for reading!!!!