python - 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
我一无所获....我想我可以尝试使用它,除非或如果其他条件,但我不知道如何。
解决方案
我找到了解决我的问题的方法。我使用 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='./')
推荐阅读
- azure-ad-b2c - Limit user access in Azure AD B2C
- sql - 用于查找记录的 Oracle 查询
- arrays - 检查字符串仅包含唯一的数组元素,重复字母
- css - 如何在 div 中而不是在窗口中打开 element-ui 抽屉
- datetime - DocusignApi Envelope.completedDateTime 使用什么偏移量
- python - 如何实现乘法表的输入?
- powershell - PowerShell:如何确定 Invoke-WebRequest 是否已超时?
- javascript - 我如何将 Google GeoChart 中不属于我的警报的一些统计数据变灰
- python - 为什么 psutil CPU 使用率太低?
- php - 带复选框的 PHP MySQL 高级搜索