Gathering facts from hosts

Hi list,

I wonder if there is a dynamic way of providing facts about hosts.

I only find the possibility to include facts that are hardcoded in one
file (or multiple), but they are static, and maybe outdated. This I see
on page
<https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#adding-custom-facts&gt;\.

Is there any way to extend facts with own facts that are rendered
dynamically and delivered on-the-fly when the setup module runs?

Currently, I use facter on each host to provice those facts. Here, I can
write scripts and put them in one certain directory, so they are
executed each time all facts are gathered. This is a facter mechanism.

I'd like to abandon facter and stick with ansible's facts, but I did not
find how to generate them on the fly.

Is it possible to have a playbook that has a first command like "run my
facts script" (which outputs some data to /etc/ansible/facts.d/somefile)
and then re-run the setup module as second step? Will the newly read
facts be available? Or are there other best practices I didn't find yet?

Regards,
Werner

You can try to copy the facts dynamically, usjng the template module while running the playbook in the custom facts directory.

To quote the second paragraph in the section you just linked, “You can […] add dynamic facts by adding executable scripts to facts.d. For example, you can add a list of all users on a host to your facts by creating and running a script in facts.d.”

You can use predefined vars that work like that, just have their
template calculate these dynamic facts, since vars use lazy evaluation
it does not matter when you define them, just when you use them (only
after the expected facts are gathered).

If I’m understanding you correctly, you’re creating facts, then you want to use the same just created facts in the same ansible run?

If this is the case, you can reload the facts and use them in the playbook using something like this:

  • name: local facts
    debug: var=ansible_local
    notify:

  • reload facts

  • name: reload facts
    setup: filter=ansible_local

I did a talk on this at Ansible-London and you can watch the video here: https://youtu.be/eNV4Z9o7-7s
I have some code examples for this here: https://github.com/dmccuk/local_facts

Or, in light of Ansible not having a “facts store”, I’ve been working on an open-source project to provide just that called Ansibledb. It lets you go off to all your servers/VMs/Windows/network devices/etc, and it collects and stores all their facts (including custom facts) in a DB which you can then query (via the API) for specific facts within your environment or just create a dynamic inventory based on a specific fact which is actually quite a useful thing to be able to do.

This is the projects home:
https://github.com/apidb-io/ansibledb_api_opensource

YT link with a demo: https://youtu.be/1vLe7o0BooY

I hope this helps.