from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager # Create an inventory manager and load the inventory from a file inventory_manager = InventoryManager(loader=None, sources='inventory.yaml') # Create a variable manager variable_manager = VariableManager(loader=None, inventory=inventory_manager) # Get all variables for a host host_vars = variable_manager.get_vars(host='example.com') print(host_vars)
from ansible.vars.manager import VariableManager from ansible.parsing.dataloader import DataLoader # Load variables from a YAML file data_loader = DataLoader() yaml_file = 'vars.yaml' vars_yaml = data_loader.load_from_file(yaml_file) # Create a variable manager using the YAML variables variable_manager = VariableManager(loader=data_loader) variable_manager.set_inventory({'_meta': {'hostvars': vars_yaml}}) # Get a variable my_var = variable_manager.get_vars()['my_var'] print(my_var)This example loads variables from a YAML file and creates a variable manager using those variables. It then retrieves the variable `my_var` and prints it. The python package library used for these examples is `ansible` which provides a set of Python modules that implement various functionalities of the Ansible IT automation platform.