-
Notifications
You must be signed in to change notification settings - Fork 1
/
inventory-vagrant.py
executable file
·56 lines (46 loc) · 1.68 KB
/
inventory-vagrant.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
#!/usr/bin/env python
# Adapted from Mark Mandel's implementation
# https://github.com/ansible/ansible/blob/stable-2.1/contrib/inventory/vagrant.py
# License: GNU General Public License, Version 3 <http://www.gnu.org/licenses/>
import argparse
import json
import subprocess
import sys
def parse_args():
parser = argparse.ArgumentParser(description="Vagrant inventory script")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true')
group.add_argument('--host')
return parser.parse_args()
def list_running_hosts():
cmd = "vagrant status --machine-readable"
status = subprocess.check_output(cmd.split()).rstrip().decode('utf-8')
hosts = []
for line in status.split('\n'):
(_, host, key, value) = line.split(',')[:4]
if key == 'state' and value == 'running':
hosts.append(host)
return hosts
def get_host_details(host):
cmd = "vagrant ssh-config {}".format(host)
p = subprocess.run(cmd.split(), stdout=subprocess.PIPE, check=True)
c = {}
for line in p.stdout.decode('utf8').split('\n'):
if line.strip() == '':
continue
[key, value] = line.strip().split(' ', 1)
c[key.lower()] = value
return {'ansible_host': c['hostname'],
'ansible_port': c['port'],
'ansible_user': c['user'],
'ansible_private_key_file': c['identityfile']}
def main():
args = parse_args()
if args.list:
hosts = list_running_hosts()
json.dump({'vagrant': hosts}, sys.stdout)
else:
details = get_host_details(args.host)
json.dump(details, sys.stdout)
if __name__ == '__main__':
main()