File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+
3+ import argparse
4+ import json
5+ import yaml
6+ import os
7+ import subprocess
8+ import sys
9+ from io import StringIO
10+
11+
12+ def parse_args ():
13+ parser = argparse .ArgumentParser (description = "Broker inventory script" )
14+ group = parser .add_mutually_exclusive_group (required = True )
15+ group .add_argument ('--list' , action = 'store_true' )
16+ group .add_argument ('--host' )
17+ return parser .parse_args ()
18+
19+
20+ def get_running_hosts ():
21+ cmd = ["broker" , "inventory" , "--details" ]
22+
23+ try :
24+ output = subprocess .check_output (cmd , universal_newlines = True ).rstrip ()
25+ except FileNotFoundError :
26+ return
27+
28+ hosts = yaml .safe_load (output )
29+ return hosts .values ()
30+
31+
32+ def list_running_hosts ():
33+ hosts = get_running_hosts ()
34+ variables = dict (get_configs (hosts ))
35+
36+ return {
37+ "_meta" : {
38+ "hostvars" : variables
39+ },
40+ "all" : {
41+ "hosts" : list (variables .keys ())
42+ },
43+ }
44+
45+
46+ def get_configs (hosts ):
47+ if not hosts :
48+ return
49+
50+ for host in hosts :
51+ details = {
52+ 'ansible_host' : host ['ip' ],
53+ 'ansible_port' : '22' ,
54+ 'ansible_user' : 'root'
55+ }
56+ yield host ['hostname' ], details
57+
58+
59+ def main ():
60+ args = parse_args ()
61+ hosts = list_running_hosts ()
62+
63+ if args .list :
64+ json .dump (hosts , sys .stdout )
65+ elif args .host :
66+ details = hosts ['_meta' ]['hostvars' ]
67+ json .dump (details [args .host ], sys .stdout )
68+
69+
70+ if __name__ == '__main__' :
71+ main ()
You can’t perform that action at this time.
0 commit comments