WARNING: The Ansible Python API is NOT officially supported, proceed at your own risk!

If you’re still with me, here’s the part of the Ansible API that I find most useful:

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager


loader = DataLoader()
inventory = InventoryManager(loader=loader, sources="./inventory/prod.ini")
vm = VariableManager(loader=loader, inventory=inventory)
primary_host_vars = vm.get_vars(host=inventory.groups['primary'].get_hosts()[0])
print(primary_host_vars['some_group_var']) 

What you see here is the API for accessing the inventory data you’ve built up including properly grouped and nested variables, like your group variables and host variables.

Note this won’t get you discovered facts (which requires connecting to remote systems), but I’ve found just accessing the local inventory data to be useful for keeping that inventory as the source of truth for helper scripts and utilities that may not be best expressed as playbooks.

Again, this is not supported, but highly useful!

As an alernate pattern remember you can export your host vars, group vars, and other inventory data as json and access that directly in your scripts like this:

ansible-inventory -i inventory/prod.ini --list