-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inventory.py
executable file
·90 lines (80 loc) · 2.45 KB
/
inventory.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Create a dynamic inventory for this ansible playbook
"""
import socket
import sys
import json
INIT_HOST=False
# create a dict to match hostnames to enviroments
env_dict = {
'work':
['macbook.local'],
'private':
['derpy.local', 'applejack.local', 'rarity.local', 'discord.local']
}
def fqdn():
"""
return fully qualified domain name
"""
hostname = socket.gethostname()
if '.' not in hostname:
hostname = f"{hostname}.local"
return str(hostname)
def become_pass(host, group):
"""
return variable for become password using gopass lookup
"""
if group == 'work':
gopasslookupprefix = 'private/ansible/hosts/'
else:
gopasslookupprefix = 'ansible/hosts/'
passstring = str("\"ansible_become_pass\": \"{{ lookup('community.general.passwordstore', '"
+ gopasslookupprefix + host + "/users/root') }}\"")
return passstring
def env(domain):
"""
map a hostname to a space
or print empty list if no one matched and exit
"""
for key, values in env_dict.items():
if domain in values:
return key
if INIT_HOST:
return str('init')
print(json.dumps(empty_host_list(domain), sort_keys=True, indent=2))
sys.exit()
def empty_host_list(domain):
"""
return empty host list
"""
comment = f"No valid host found. Found '{domain}'. Return empty host list!"
return json.loads('{"_meta": {"comment": "' + comment +
'", "hostvars": {}}, "instances": {"hosts": []}}')
def hostvars(host, group):
"""
set variables to local connection
"""
local = str('"' + host + '": {"ansible_connection": "local"')
if not INIT_HOST:
local += str(', ' + str(become_pass(host, group)))
local += str('}')
return local
def formated_host_group_list(host, group):
"""
build inventory and return it
"""
# pylint: disable=line-too-long
return json.loads('{"_meta": {"hostvars": {' + str(hostvars(host, group)) + '}},"' + str(group) + '": {"hosts": ["' + str(host) + '"]},"instances": {"children": ["' + str(group) + '"]}}')
def main():
"""
main funktion
will analyse on which host this script is started
and will print the dynamic inventory to tell ansible
which host_vars and group_vars should be used
"""
host = fqdn()
group = env(host)
print(json.dumps(formated_host_group_list(host, group), sort_keys=True, indent=2))
main()