Getting facts from hosts that are not the target of a playbook

Hello Ansible Experts,

How would I get a fact/variable from a host that is not the target of my playbook?

I know that hostvars exist for this reason but since the hosts that I want to get variables from are not the target of my playbook, the hostvars for that host is not populated.

For this scenario, I am generating a configuration file for a Munin master node which needs to get the ansible_processor_count from the other nodes. This playbook is executed for the master node only so therefore only the facts for that master node are gathered.

Here’s the Jinja template that I am trying to render:

{% for host in groups[‘all’] %}
[{{ host }}]
address {{ host }}
use_node_name yes
cpu.user.warning {{ hostvars[host][‘ansible_processor_count’] * 100 * 0.8 }}
cpu.user.critical {{ hostvars[host][‘ansible_processor_count’] * 100 * 0.9 }}
{% endfor %}

I get a:

fatal: [munin-master] => {‘msg’: “‘dict object’ has no attribute ‘ansible_processor_count’”, ‘failed’: True}

Thank you!

Paulo

Sure, basically you just need a dummy play that talks to the host prior to referencing it, like so:

  • hosts: other_hosts # you could put ‘all’ here if you want to, even
    tasks:

  • hosts: main_group_of_hosts
    tasks:

  • your regular tasks from above go here

Once you will have already talked to those other hosts, their facts will be available via hostvars.

Hello,

It seems ok in a regular playbook, since the dummy call would be in the same file or context.

But I believe this is not very clean when required from a role: having a reusable piece of functionality in differing contexts assume a dummy play was called seems error prone.

Thanks

The code path is reliable.

You just need do to something like

  • name: ‘gather facts on all hosts’
    hosts: all
    tasks:

  • name: “do stuff”
    hosts: whatever
    roles:

In any event, we’ll probably consider caching facts in a future release, although you would still need to talk to each host at least once.