通过(python)

时间:2016-08-28 03:59:08

标签: python ansible

我正在尝试查询Ansible中设置的全局组变量。我似乎得到一个空字典,我不知道我还能做什么。我的代码如下所示:

def __init__(self, inventory_path=None):
    self.loader = DataLoader()
    self.variable_manager = VariableManager()
    self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=inventory_path)
    self.variable_manager.set_inventory(self.inventory)

然后我尝试获得如下的组变量:

    inventory_asg_groups = filter(lambda g: 'asg' in g, self.inventory.groups)
    for group in inventory_asg_groups:
        print(self.inventory.get_group_vars(self.inventory.get_group(group)))

我得到一个空字典:

{}

当我做一个:

    print(self.inventory.localhost.vars)

我明白了:

{'ansible_python_interpreter': '/usr/local/opt/python/bin/python2.7', 'ansible_connection': 'local'}

我知道正在加载库存,因为我列出了库存中的所有组。如何通过python ansible api获取 group_vars / all 中列出的变量?

1 个答案:

答案 0 :(得分:1)

如果您定义了特定于组的变量(group_vars / .yml),则此方法实际上有效。这是因为get_group_vars直接读取“所有”,您可以使用self.inventory.get_group_vars(self.inventory.get_group('all'))

下面的完整示例:

污垢/主机

# hosts
[asg_2]

localhost1

[asg_1]
localhost2

[something]
localhost3

dir / group_vars / all.yml

setting_something: "5"

dir / group_vars / ags_1.yml

setting_something: "6500"

dir / ansible_loader.py

from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory

class AnsibleLoader:
    def __init__(self, inventory_path=None):
        self.loader = DataLoader()
        self.variable_manager = VariableManager()
        self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=inventory_path)
        self.variable_manager.set_inventory(self.inventory)

        inventory_asg_groups = filter(lambda g: 'asg' in g, self.inventory.groups)

        print(inventory_asg_groups)
        for group in inventory_asg_groups:
            print('vars for: %s' % group)
            print(self.inventory.get_group_vars(self.inventory.get_group(group)))

        print(self.inventory.get_group_vars(self.inventory.get_group('all')))


AnsibleLoader(inventory_path='hosts')

输出

[u'asg_2', u'asg_1']
vars for: asg_2
{}
vars for: asg_1
{u'setting_something': u'6500'}
{u'setting_something': u'5'}

因此,它在group_vars中有文件时会打印asg_1的值,但不会为asg_2打印。最后一行正在访问“全部”

所有操作均通过ansible 2.0完成,不确定使用的版本。