arviasf
unread,Jan 5, 2022, 3:55:00 PM1/5/22Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ansible Project
Hi folks - In a standalone Python script, I need to enumerate and expand all host variables from a given Ansible inventory file. In this inventory file, there are variables which reference other variables using Jinja2 templates, and the level of recursion in those can be 3-4 levels deep. Some of the vars use Jinja2 tests (such as the version (version_compare) test) within their templates.
After some experimentation I could combine Ansible libraries with Jinja2 to do this. But it looks like a lot of work. Is there an intrinsic way to use ansible Python API and recursively expand all host variables?
FYI, here is what currently works for me:
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager
from ansible.plugins.test.core import version_compare
from jinja2 import Template, Environment
sources = ['/project/ansible/conf/hosts']
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources=sources)
variable_manager = VariableManager(loader=loader, inventory=inventory)
myhost = inventory.get_hosts()[0]
vars = variable_manager.get_vars(host = myhost)
environment = Environment()
environment.tests["version"] = version_compare
for k, v in vars.items():
if type(v) == str:
expanded_value = environment.from_string(v)
while True:
expanded_value = expanded_value.render(vars)
if "{{" not in expanded_value:
break
else:
expanded_value = environment.from_string(expanded_value)
print(k, ":", expanded_value)