如何通过 Python API 获取层次结构中的所有库存组变量?

How to get all inventory groups variables in hierarchy via Python API?

我想收集层次结构数据结构中的所有清单主机组变量,并将它们发送给 Consul 以使其在运行时可用。

调用此方法 - https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L160 我收到错误

inventory.get_vars()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    inventory.get_vars()
  File "<>/.virtualenvs/ansible27/lib/python2.7/site-packages/ansible/inventory/manager.py", line 160, in get_vars
    return self._inventory.get_vars(args, kwargs)
AttributeError: 'InventoryData' object has no attribute 'get_vars'

我的脚本

import pprint
pp = pprint.PrettyPrinter(indent=4).pprint

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='inventories/itops-vms.yml')
variable_manager = VariableManager(loader=loader, inventory=inventory)

# shows groups as well
pp(inventory.groups)

# shows dict as well with content
pp(variable_manager.get_vars())

# creates an unhandled exception
inventory.get_vars()

如何正确地做到这一点?

错误本身似乎是由错误引起的 - 清单对象的 get_vars 方法调用了未实现的 InventoryData 对象的 get_vars 方法。


您需要指定群组,例如:

>>> inventory.groups['all'].get_vars()
{u'my_var': u'value'}

您可以使用该数据创建字典:

{g: inventory.groups[g].get_vars() for g in inventory.groups}

上面只获取了库存本身定义的变量(这就是问题所问的)。如果您想获得一个包含来自 group_vars、host_vars 等变量的结构(正如您在评论 中指出的那样,您需要从不同来源收集数据,就像Ansible 可以。