Skip to main content
 首页 » 编程设计

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

2024年12月31日8sharpest

我想收集层次结构数据结构中的所有 list 主机组变量,并将它们发送给 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
  • Mac 高 Siera 操作系统

请您参考如下方法:

错误本身似乎是由错误引起的——库存对象的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} 

以上仅获取 list 本身中定义的变量(这就是问题所问的内容)。如果您想获得一个包含来自 group_vars、host_vars 等变量的结构(如您在评论 I want to get something similar to $ ansible-inventory -i inventories/itops-vms.yml --graph --vars 中指出的那样),您需要从不同来源收集数据,就像 Ansible 所做的那样。