首页 > 解决方案 > ansible.inventory.manager 检查库存是否存在 python 错误

问题描述

我有一个错误的 Ansible hosts.ini

[linux]
server01 pr_ip_address = 10.0.0.1

我在python中编写了以下函数

from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader

def check_inventory():
    loader = DataLoader()
    InventoryManager(loader=loader, sources='hosts.ini')

check_inventory()

我正在尝试将以下消息用作 stderr :

[WARNING]:  * Failed to parse
/inventories/hosts.ini  
with script plugin: problem running
/hosts.ini  
--list ([Errno 8] Exec format error: '/hosts.ini')
[WARNING]:  * Failed to parse
/hosts.ini  
with ini plugin: /hosts.ini:913: Expected key=value host variable assignment, got:
pr_ip_address
[WARNING]: Unable to parse
/hosts.ini  
as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available

我的问题,我不知道要抓住它,也不能把它写到stderr或stdout。

当我的ini文件正确时:

[linux]
server01 pr_ip_address=10.0.0.1

我一无所获....我想我可以尝试使用它,除非或如果其他条件,但我不知道如何。

标签: pythonapiansibleansible-inventoryinventory

解决方案


我找到了解决我的问题的方法。我使用 ansible_runner 并捕获它的输出。这对我很有效:)。也许它也对其他人有帮助!

import os
import sys
import ansible_runner
from io import StringIO 
from termcolor import colored, cprint


def verify(inipath):
    class Capturing(list):
        def __enter__(self):
            self._stdout = sys.stdout
            sys.stdout = self._stringio = StringIO()
            return self
        def __exit__(self, *args):
            self.extend(self._stringio.getvalue().splitlines())
            del self._stringio    # free up some memory
            sys.stdout = self._stdout

    with Capturing() as output:
        r = ansible_runner.run(private_data_dir=inipath, 
                            inventory='hosts.ini', 
                            host_pattern='localhost', 
                            module='shell', 
                            module_args='whoami')
        print(r.status, str)


    def words_in_string(word_list, a_string):
        return set(word_list).intersection(a_string.split())

    error_handling = ['error', 'Failed', 'Errno']

    if words_in_string(error_handling, str(output)):
        print(output)
        cprint('something went wrong with your hosts.ini :(', 'green')
        sys.exit(0)
    else:
        cprint('hosts.ini verify was successfully!!!', 'green')
        pass

if __name__ == "__main__":
    verify(inipath='./')

推荐阅读