Customizing Fact Gathering
While Ansible's built-in fact gathering is powerful, there may be times when you need to collect additional information or customize the fact gathering process. LabEx provides several ways to extend and customize the fact gathering capabilities of Ansible.
Custom Fact Modules
Ansible allows you to write your own fact modules to gather additional information about your managed hosts. These custom fact modules can be written in any language supported by Ansible, such as Python, Bash, or PowerShell.
Here's an example of a custom fact module written in Python that gathers information about the installed packages on an Ubuntu 22.04 system:
#!/usr/bin/env python
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(),
supports_check_mode=True
)
packages = []
with open('/var/lib/dpkg/status', 'r') as f:
for line in f:
if line.startswith('Package:'):
packages.append(line.split(':')[1].strip())
module.exit_json(changed=False, ansible_facts={'installed_packages': packages})
if __name__ == '__main__':
main()
To use this custom fact module, you can include it in your Ansible playbook:
- hosts: all
gather_facts: false
tasks:
- name: Gather custom facts
ansible.builtin.setup:
gather_subset:
- custom
register: custom_facts
- name: Print custom facts
debug:
var: custom_facts.ansible_facts.installed_packages
This will gather the list of installed packages and make it available as an Ansible fact.
Fact Caching
Ansible supports fact caching, which can improve the performance of your playbooks by reducing the time required to gather facts. You can enable fact caching by configuring the fact_caching
option in your Ansible configuration file or playbook.
Here's an example of how to enable fact caching using the memory
fact cache plugin:
- hosts: all
gather_facts: true
strategy: free
vars:
ansible_facts_cache_plugin: memory
ansible_facts_cache_timeout: 86400 ## 1 day
This will cache the gathered facts in memory for 24 hours, reducing the time required to gather facts on subsequent runs.
By leveraging custom fact modules and fact caching, you can extend Ansible's fact gathering capabilities to better suit your specific requirements and improve the performance of your automation workflows.