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

时间:2018-08-10 17:55:56

标签: python automation ansible devops

我想收集层次结构数据结构中的所有清单主机组变量,并将它们发送给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()

如何正确处理?

  • Python 2.7.15
  • ansible == 2.6.2
  • OS Mac High Siera

1 个答案:

答案 0 :(得分:1)

错误本身似乎是由错误引起的-库存对象的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等中获取带有变量的结构(如您在评论I want to get something similar to $ ansible-inventory -i inventories/itops-vms.yml --graph --vars中所指出的那样,则您需要像Ansible一样从不同来源收集数据。 < / p>