Skip to content

Commit 291db2a

Browse files
committed
Add inventory for working with broker
1 parent dd77abd commit 291db2a

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

inventories/broker.py

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#!/usr/bin/env python
2+
3+
import argparse
4+
import json
5+
import yaml
6+
import os
7+
import subprocess
8+
import sys
9+
10+
try:
11+
from StringIO import StringIO # pyright: reportMissingImports=false
12+
except ImportError:
13+
from io import StringIO # pyright: reportMissingImports=false
14+
15+
from collections import defaultdict
16+
17+
18+
try:
19+
DEVNULL = subprocess.DEVNULL
20+
except AttributeError:
21+
DEVNULL = open(os.devnull, 'w')
22+
23+
24+
def parse_args():
25+
parser = argparse.ArgumentParser(description="Broker inventory script")
26+
group = parser.add_mutually_exclusive_group(required=True)
27+
group.add_argument('--list', action='store_true')
28+
group.add_argument('--host')
29+
return parser.parse_args()
30+
31+
32+
def get_running_hosts():
33+
try:
34+
subprocess.check_call(["which", "broker"], stdout=DEVNULL)
35+
except subprocess.CalledProcessError:
36+
return
37+
38+
cmd = "broker inventory --details"
39+
output = subprocess.check_output(cmd.split(), universal_newlines=True).rstrip()
40+
41+
hosts = yaml.safe_load(output)
42+
return hosts.values()
43+
44+
45+
def list_running_hosts():
46+
hosts = get_running_hosts()
47+
variables = dict(get_configs(hosts))
48+
49+
return {
50+
"_meta": {
51+
"hostvars": variables,
52+
},
53+
"all": {
54+
"hosts": [host['hostname'] for host in hosts],
55+
},
56+
}
57+
58+
59+
def get_configs(hosts):
60+
if not hosts:
61+
return
62+
63+
for host in hosts:
64+
details = {
65+
'ansible_host': host['ip'],
66+
'ansible_port': '22',
67+
'ansible_user': 'root'
68+
}
69+
yield host['hostname'], details
70+
71+
72+
def main():
73+
args = parse_args()
74+
hosts = list_running_hosts()
75+
76+
if args.list:
77+
json.dump(hosts, sys.stdout)
78+
elif args.host:
79+
details = hosts['_meta']['hostvars']
80+
json.dump(details[args.host], sys.stdout)
81+
82+
83+
if __name__ == '__main__':
84+
main()

0 commit comments

Comments
 (0)