方法一:通过最原始的操作文件的方式

Python调用ansible API系列(四)动态生成hosts文件 随笔 第1张
#!/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()
View Code

Python调用ansible API系列(四)动态生成hosts文件 随笔 第3张

方法二:通过数据库或者调用其他API获取数据来动态获得

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄