Reputation: 3055
How do I get just the hostlist using ansible API. I want the equivalent of the below command using the ansible python API.
ansible all --list-host
EDIT:
Is this the right way?
inventory = ansible.inventory.Inventory(options.inventory)
for h in inventory.host_list():
print h
Upvotes: 2
Views: 375
Reputation: 404
Like this:
import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources=['PATH_TO_INVENTORY_FILE'])
variable_manager = VariableManager(loader=loader, inventory=inventory)
myhosts = variable_manager.get_vars()['groups']['all']
Please notice that PATH_TO_INVENTORY_FILE can be absolute or relative to the current directory, so you could do something like "./inventory/hosts"
Also be aware in there 'all' the hosts will be gathered. If you'd want to filter a specific group just specify the name of the group instead of 'all'.
Upvotes: 1