Load facts just-in-time

Hi,

Is there a pattern to collect facts just-in-time (JIT)?

Reason:

I use dynamic facts using facts.d (Discovering variables: facts and magic variables — Ansible Documentation).

All facts are collected when any Ansible playbook runs on the controller.

Collecting these facts is slow (inherent to my systems, not able to speed that up more). While I only need them for some playbooks.

Playbooks that do not use these facts would be sped up enormously, if Ansible loads the fact only when it’s accessed by its ansible_local.$fact notation.

Of course, this would require Ansible to know which local facts exist, and which facts.d script it needs to run to collect a specific one. A pattern which I haven’t been able to find.

I’m not quite sure if I’ve understood your question correctly, but you don’t necessarily have to do “gathering facts” at the beginning of your playbook.

You can use gather_facts: no to not create any at first and work through something and if you get to a point where you need it, then you just do it later.

- name: Gather facts
  setup:

I hope this can help?

1 Like

I do want to gather facts, just not specific ones that are expensive to get and are not always needed.

gather_facts does not allow me to exclude facts / facts files selectively.

You’re right, but I don’t think there’s a solution for that.
With automation, the throughput is not so relevant for me.

But what I can think of for a basic acceleration would be that you build up your dynamic inventory cyclically with ansible-inventory and store it as a static json file.
You can then use this in the playbook executions. This eliminates the longer waiting time at the start of execution. But the disadvantage is, of course, that the data is never 100% up-to-date. But it could perhaps be a possibility.

1 Like

setup and gather_facts support filtering and gathering specific subsets of facts.

    - name: Gather only local facts
      gather_facts:
        gather_subset: "!all,!min,local"
        filter: "ansible_local"  # <- redundant since only local facts are gathered

Valid subsets are documented here ansible.builtin.setup module – Gathers facts about remote hosts — Ansible Community Documentation.

3 Likes