ansible.inventory.manager 在 python 中检查库存是否有错误

时间:2021-01-18 21:16:09

标签: python api ansible ansible-inventory inventory

我有一个 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()

我正在尝试使用以下消息作为标准错误:

[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

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

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。我使用 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='./')