How to access hostvars of other host inside testinfra/ansible code

… wich is inside verifier inside Molecule scenario, inside your CI job, inside … ah, doesn’t matter.

George Shuklin
OpsOps
1 min readNov 25, 2020

--

Either you have no idea what this article is about, or you desperately want it.

The problem

I have Molecule running testinfra verifier. It uses Ansible integration inside testinfra to do tests. Inside my test I need to access hostvars of other host in the inventory. (This inventory is automatically generated by molecule, btw).

The solution

If you have fixture host (you need one to do normal tests), that it’s there:

host.backend.ansible_runner.inventory['_meta']['hostvars']

I have no idea why it’s here, why it has private _meta, etc. But it’s here.

With icing on top

If you ever got in such situation, there is 99.42% chance you need to to get to ‘other host in the group’ variables. That means you:

  • need to know your group (usually not a problem as tests are run against pre-defined group).
  • need to know you own hostname to skip.
  • need to get a host from a group without ‘you’.

To get you inventory_hostname you can call function host.backend.get_hostname()

To find ‘any other host in the group VM except for myself’, this snippet works:

set(host.backend.ansible_runner.inventory['vms']['hosts']) - set([host.backend.get_hostname()])

And if you need ‘any other host from the group variables’, this is a complete code:

inventory = host.backend.ansible_runner.inventory
inventory_hostname = host.backend.get_hostname()
other_host = (set(inventory['vms']['hosts']) - \
set([inventory_hostname])).pop()
other_host_vars = inventory['_meta']['hostvars'][other_host]

(in this code ‘vms’ is an arbitrary group, the rest should be as it is).

P.S. testinfra is a good thing, but ansible integration is far from perfect…

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.