方法一:通过最原始的操作文件的方式
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过操作文件形式动态生成ansible的hosts文件 """ import sys class Inventory: def __init__(self): # ansible的hosts文件路径 self._hostsfile = "./aaa" self._data = self._getInventoryInfo() if self._genHostsFile(): print("生成完成。") else: print("生成失败。") def _getInventoryInfo(self): """ 从数据库中获取资产信息 :return: """ tempdata = [ { "Groupname": "Group1", "Items": [ { "name": "Srv01", "ansible_ssh_host": "172.16.100.20", "ansible_ssh_port": "22", "ansible_ssh_user": "work", "ansible_python_interpreter": "/usr/bin/python" }, { "name": "Srv02", "ansible_ssh_host": "172.16.100.30", "ansible_ssh_port": "22", "ansible_ssh_user": "work", "ansible_python_interpreter": "/usr/bin/python" }, ] }, ] return tempdata def _genHostsFile(self): """ 生成资产hosts文件 :return: 生成成功返回True """ try: with open(self._hostsfile, "w") as file1: for i in self._data: groupname = i.get("Groupname") file1.write("["+groupname+"]\n") for server in i.get("Items"): name = server.get("name") ansible_ssh_host = server.get("ansible_ssh_host") ansible_ssh_port = server.get("ansible_ssh_port") ansible_ssh_user = server.get("ansible_ssh_user") ansible_python_interpreter = server.get("ansible_python_interpreter") info = "ansible_ssh_host={0} ansible_ssh_port={1} ansible_ssh_user={2} ansible_python_interpreter={3}". format(ansible_ssh_host, ansible_ssh_port, ansible_ssh_user, ansible_python_interpreter) line = name + " " + info + "\n" file1.write(line) except Exception as err: print(err) return False return True def main(): Inventory() if __name__ == "__main__": try: main() finally: sys.exit()
方法二:通过数据库或者调用其他API获取数据来动态获得
原文地址:https://www.cnblogs.com/yunxizhujing/p/10677716.html
时间: 2024-11-05 20:43:33