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

前端 未结 1 755
南方客
南方客 2021-02-12 16:36

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 ser

1条回答
  •  有刺的猬
    2021-02-12 17:38

    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):

    
    [{'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'}}]
    

    0 讨论(0)
提交回复
热议问题