-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost_file.py
More file actions
61 lines (48 loc) · 1.82 KB
/
host_file.py
File metadata and controls
61 lines (48 loc) · 1.82 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
57
58
59
60
61
import yaml
class CustomString(str):
'''Allow different configurations on the same host'''
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
def getHostConfig(fileToParse) -> dict:
config: dict = yaml.safe_load(fileToParse)
if not config.get('hosts'):
raise ValueError('"hosts" key is missing or empty')
default = config.get('default', {})
default.setdefault('sudoRequiresPassword', True)
if not isinstance(default, dict):
raise TypeError('"default" key must be an object')
hostConfig = {}
for index, host in enumerate(config['hosts']):
if not isinstance(host, dict):
raise TypeError(f'host {index + 1} is not an object')
name, config = makeConfigForHost(host, default)
if name in hostConfig:
raise ValueError(f'host {name} is duplicate')
hostConfig[name] = config
return hostConfig
def makeConfigForHost(currentHost: dict, default: dict):
config: dict = default.copy()
config.update(currentHost)
return CustomString(config.get('host')), config
_example = {
'default': {
'user': 'username (str)',
'password': 'password to use (str)',
'port': 'port (int)',
'sudoRequiresPassword': 'if sudo requires sending the password. default true (bool)',
'name': 'optional name of the host to use when logging (str)'
},
'hosts': [{
'host': 'host name. Required',
'user': 'username',
'password': 'password to use'
}]
}
def saveExample(fileName: str):
if not any(fileName.casefold().endswith(ext) for ext in ('yaml', 'yml')):
fileName += '.yaml'
with open(fileName, 'w') as f:
yaml.dump(_example, f, default_flow_style=False)
print(f'Saved example configuration to {fileName}')