如何从Ansible清单文件中获取主机列表?

时间:2016-06-03 21:39:14

标签: python ansible ansible-2.x

有没有办法使用Ansible Python API从给定的库存文件/组合组合中获取主机列表?

例如,我们的库存文件按服务类型拆分:

[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

我是否可以以某种方式使用ansible.inventory传递特定的广告资源文件,以及我想要操作的组,并让它返回匹配的主机列表?

5 个答案:

答案 0 :(得分:13)

从以前做同样的技巧,但不是all,而是传递你想要列出的组名:

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

答案 1 :(得分:7)

我一直在努力解决这个问题,但是通过试验找到了一个解决方案。错误。

API的一个主要优势是您可以提取变量和元数据,而不仅仅是主机名。

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
)

这为您提供了一个Inventory实例,它具有提供组和主机的方法和属性。

为了进一步扩展(并提供Group和Host类的示例),这里是我写的一个片段,它将清单序列化为一个组列表,每个组都有一个'hosts'属性,它是每个主机属性的列表。

#/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)

我在四个F5 BIG-IP的实验室中运行了这个,这是结果(修剪):

<!-- 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'}}]

答案 2 :(得分:3)

对我来说,工作

List<?>

inventory.get_groups_dict()返回一个字典,您可以使用group_name作为密钥来获取主机,如代码中所示。 你必须按照以下方式安装你可以做的ansible包

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager

if __name__ == '__main__':
    inventory_file_name = 'my.inventory'
    data_loader = DataLoader()
    inventory = InventoryManager(loader = data_loader,
                             sources=[inventory_file_name])

    print(inventory.get_groups_dict()['spark-workers'])

答案 3 :(得分:1)

我遇到了类似的问题,我认为nitzmahone的方法是不使用不受支持的Python API调用。这是一个有效的解决方案,依赖于ansible-inventory CLI的JSON格式输出:

pip install ansible==2.4.0.0 sh==1.12.14

示例清单文件inventory/qa.ini

[lxlviewer-server]
id-qa.kb.se

[xl_auth-server]
login.libris.kb.se

[export-server]
export-qa.libris.kb.se

[import-server]
import-vcopy-qa.libris.kb.se

[rest-api-server]
api-qa.libris.kb.se

[postgres-server]
pgsql01-qa.libris.kb.se

[elasticsearch-servers]
es01-qa.libris.kb.se
es02-qa.libris.kb.se
es03-qa.libris.kb.se

[tomcat-servers:children]
export-server
import-server
rest-api-server

[flask-servers:children]
lxlviewer-server
xl_auth-server

[apache-servers:children]
lxlviewer-server

[nginx-servers:children]
xl_auth-server

用于提取信息的Python 2.7函数(可轻松扩展到hostvars等):

import json
from sh import Command

def _get_hosts_from(inventory_path, group_name):
    """Return list of hosts from `group_name` in Ansible `inventory_path`."""
    ansible_inventory = Command('ansible-inventory')
    json_inventory = json.loads(
        ansible_inventory('-i', inventory_path, '--list').stdout)

    if group_name not in json_inventory:
        raise AssertionError('Group %r not found.' % group_name)

    hosts = []
    if 'hosts' in json_inventory[group_name]:
        return json_inventory[group_name]['hosts']
    else:
        children = json_inventory[group_name]['children']
        for child in children:
            if 'hosts' in json_inventory[child]:
                for host in json_inventory[child]['hosts']:
                    if host not in hosts:
                        hosts.append(host)
            else:
                grandchildren = json_inventory[child]['children']
                for grandchild in grandchildren:
                    if 'hosts' not in json_inventory[grandchild]:
                        raise AssertionError('Group nesting cap exceeded.')
                    for host in json_inventory[grandchild]['hosts']:
                        if host not in hosts:
                            hosts.append(host)
        return hosts

证明它有效(也适用于儿童和孙子团体):

In [1]: from fabfile.conf import _get_hosts_from

In [2]: _get_hosts_from('inventory/qa.ini', 'elasticsearch-servers')
Out[2]: [u'es01-qa.libris.kb.se', u'es02-qa.libris.kb.se', u'es03-qa.libris.kb.se']

In [3]: _get_hosts_from('inventory/qa.ini', 'flask-servers')
Out[3]: [u'id-qa.kb.se', u'login.libris.kb.se']

In [4]:

答案 4 :(得分:0)

自批准的答案以来,Ansible API发生了更改:

这适用于Ansible 2.8(甚至更多)

这是我访问大多数数据的方式:

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager


loader = DataLoader()
# Sources can be a single path or comma separated paths
inventory = InventoryManager(loader=loader, sources='path/to/file')

# My use case was to have all:vars as the 1st level keys, and have groups as key: list pairs.
# I also don't have anything ungrouped, so there might be a slightly better solution to this.
# Your use case may be different, so you can customize this to how you need it.
x = {}
ignore = ('all', 'ungrouped')
x.update(inventory.groups['all'].serialize()['vars'])
group_dict = inventory.get_groups_dict()

for group in inventory.groups:
    if group in ignore:
        continue
    x.update({
        group: group_dict[group]
    })

示例:

输入:

[all:vars]
x=hello
y=world

[group_1]
youtube
google

[group_2]
stack
overflow

输出:

{"x":"hello","y":"world","group_1":["youtube","google"],"group_2":["stack","overflow"]}

同样,您的用例可能与我的用例不同,因此您必须将代码稍微更改为您想要的样子。