create_hosts.py 2.01 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys

class Inventory():

    def __init__(self, hosts_path, group, hosts_list, user, passwd):

        # ansible的hosts文件路径
        self._hostsfile = hosts_path
        self._data = self._getInventoryInfo(group, hosts_list, user, passwd)
        if not self._genHostsFile():
            print("生成失败临时hosts失败!")
            sys.exit()

    def _getInventoryInfo(self, group, hosts_list, user, passwd):
        tempdata = {"Groupname": group, "Items": []}
        for host in hosts_list:
            tempdata['Items'].append(
                {
                    "ansible_ssh_host": host,
                    "ansible_ssh_user": user,
                    "ansible_ssh_pass": passwd,
                    "ansible_sudo_pass": passwd
                }
             )

        return tempdata

    def _genHostsFile(self):
        """
        生成hosts文件
        :return: 生成成功返回True
        """
        try:
            with open(self._hostsfile, "a") as f:
                groupname = self._data.get("Groupname")
                f.write("["+groupname+"]\n")
                for server in self._data.get("Items"):
                    ansible_ssh_host = server.get("ansible_ssh_host")
                    ansible_ssh_user = server.get("ansible_ssh_user")
                    ansible_ssh_pass = server.get("ansible_ssh_pass")
                    ansible_sudo_pass = server.get("ansible_sudo_pass")

                    info = "{0} ansible_ssh_user={1} ansible_ssh_pass={2} ansible_sudo_pass={3}".\
                        format(ansible_ssh_host, ansible_ssh_user, ansible_ssh_pass, ansible_sudo_pass)
                    line = info + "\n"
                    f.write(line)
        except Exception as err:
            print(err)
            return False
        return True

if __name__ == "__main__":
    hosts_list=['192.168.8.100', '192.168.8.101', '192.168.8.102', '192.168.8.103', '192.168.8.105']
    Inventory('tmp_hosts', 'tx2', hosts_list, 'ubuntu', 'ubuntu')