create_hosts.py
2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/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')