Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of hosts from an Ansible inventory file?

Tags:

Is there a way to use the Ansible Python API to get a list of hosts from a given inventory file / group combination?

For example, our inventory files are split up by service type:

[dev:children] dev_a dev_b  [dev_a] my.host.int.abc.com  [dev_b] my.host.int.xyz.com   [prod:children] prod_a prod_b  [prod_a] my.host.abc.com  [prod_b] my.host.xyz.com 

Can I use ansible.inventory in some way to pass in a specific inventory file, and the group I want to act on, and have it return a list of hosts that match?

like image 398
MrDuk Avatar asked Jun 03 '16 21:06

MrDuk


People also ask

How do I list groups in Ansible inventory?

Method #1 - Using Ansible If you just want a list of the groups within a given inventory file you can use the magic variables as mentioned in a couple of the other answers. In this case you can use the groups magic variable and specifically just show the keys() in this hash (keys + values).

Where can I find Ansible hosts?

Open the default hosts file (/etc/ansible/hosts) using your favorite text editor to see what an Ansible hosts file looks like. By default, Ansible looks for the hosts in the /etc/ansible/hosts file. The default inventory file contains different examples you can use as references while setting up your inventory.

How do I view Ansible inventory files?

Once you have an inventory file set up, you can use the ansible-inventory command to validate and obtain information about your Ansible inventory: ansible-inventory -i inventory --list.

What is used to identify hosts in Ansible?

nmap inventory – Uses nmap to find hosts to target — Ansible Documentation.


2 Answers

Do the same trick from before, but instead of all, pass the group name you want to list:

ansible (group name here) -i (inventory file here) --list-hosts

like image 89
nitzmahone Avatar answered Nov 12 '22 23:11

nitzmahone


I was struggling with this as well for awhile, but found a solution through trial & error.

One of the key advantages to the API is that you can pull variables and metadata, not just hostnames.

Starting from Python API - Ansible Documentation:

#!/usr/bin/env python #  Ansible: initialize needed objects variable_manager = VariableManager() loader = DataLoader()  #  Ansible: Load inventory inventory = Inventory(     loader = loader,     variable_manager = variable_manager,     host_list = 'hosts', # Substitute your filename here ) 

This gives you an Inventory instance, which has methods and properties to provide groups and hosts.

To expand further (and provide examples of Group and Host classes), here's a snippet I wrote which serializes the inventory as a list of groups, with each group having a 'hosts' attribute that is a list of each host's attributes.

#/usr/bin/env python def serialize(inventory):     if not isinstance(inventory, Inventory):         return dict()      data = list()     for group in inventory.get_groups():         if group != 'all':             group_data = inventory.get_group(group).serialize()              #  Seed host data for group             host_data = list()             for host in inventory.get_group(group).hosts:                 host_data.append(host.serialize())              group_data['hosts'] = host_data             data.append(group_data)      return data  #  Continuing from above serialized_inventory = serialize(inventory) 

I ran this against my lab of four F5 BIG-IP's, and this is the result (trimmed):

<!-- language: lang-json --> [{'depth': 1,   'hosts': [{'address': u'bigip-ve-03',              'name': u'bigip-ve-03',              'uuid': UUID('b5e2180b-964f-41d9-9f5a-08a0d7dd133c'),              'vars': {u'hostname': u'bigip-ve-03.local',                       u'ip': u'10.128.1.130'}}],   'name': 'ungrouped',   'vars': {}},  {'depth': 1,   'hosts': [{'address': u'bigip-ve-01',              'name': u'bigip-ve-01',              'uuid': UUID('3d7daa57-9d98-4fa6-afe1-5f1e03db4107'),              'vars': {u'hostname': u'bigip-ve-01.local',                       u'ip': u'10.128.1.128'}},             {'address': u'bigip-ve-02',              'name': u'bigip-ve-02',              'uuid': UUID('72f35cd8-6f9b-4c11-b4e0-5dc5ece30007'),              'vars': {u'hostname': u'bigip-ve-02.local',                       u'ip': u'10.128.1.129'}},             {'address': u'bigip-ve-04',              'name': u'bigip-ve-04',              'uuid': UUID('255526d0-087e-44ae-85b1-4ce9192e03c1'),              'vars': {}}],   'name': u'bigip',   'vars': {u'password': u'admin', u'username': u'admin'}}] 
like image 20
Theo Avatar answered Nov 13 '22 00:11

Theo