LLI Wiki — My Digital Knowledge Base

Ansible custom facts

Create an Ansible custom fact in facts.d and use it in a playbook.

Ansible facts describe the state of a managed host. A custom fact is a .fact file placed in /etc/ansible/facts.d/; Ansible collects it with the other facts and playbooks can use it.

Display the facts of a host

ansible <managed-host> -m setup

Create a custom fact

Create the directory, then the httpd.fact file:

sudo mkdir -p /etc/ansible/facts.d
sudo vim /etc/ansible/facts.d/httpd.fact

File content:

[basic]
package=httpd
service=httpd
state=started
enabled=true

Check that the fact is collected:

ansible host01.example.com -m setup | less

Use the custom fact in a playbook

---
- name: Install httpd
  hosts: host01.example.com
  tasks:
    - name: Install httpd
      yum:
        name: "{{ ansible_facts['ansible_local']['httpd']['basic']['package'] }}"
        state: latest

    - name: Start and enable httpd
      service:
        name: "{{ ansible_facts['ansible_local']['httpd']['basic']['service'] }}"
        state: "{{ ansible_facts['ansible_local']['httpd']['basic']['state'] }}"
        enabled: "{{ ansible_facts['ansible_local']['httpd']['basic']['enabled'] }}"

Notes

Mastodon LLIMastodon SocialFosstodon