如何从 Ansible 清单文件中获取主机列表? [英] How can I get a list of hosts from an Ansible inventory file?

查看:25
本文介绍了如何从 Ansible 清单文件中获取主机列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我可以以某种方式使用 ansible.inventory 来传递特定的清单文件和我想要操作的组,并让它返回匹配的主机列表吗?

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?

推荐答案

我也为此苦苦挣扎了一段时间,但通过试用 & 找到了解决方案错误.

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

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

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

Python API - Ansible 文档开始:

#!/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 实例,该实例具有提供组和主机的方法和属性.

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

为了进一步扩展(并提供 Group 和 Host 类的示例),这是我编写的一个片段,它将库存序列化为一组组列表,每个组都有一个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)

我对我的四个 F5 BIG-IP 实验室进行了测试,结果如下(修剪后):

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

这篇关于如何从 Ansible 清单文件中获取主机列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆