-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjailventory.py
executable file
·71 lines (56 loc) · 1.95 KB
/
jailventory.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
#!/usr/local/bin/python2.7
# Ansible dynamic inventory provider for FreeBSD jails. Details:
# https://docs.ansible.com/ansible/2.6/dev_guide/developing_inventory.html
#
# Dimitris Karagkasidis, <t.pagef.lt@gmail.com>
# https://github.com/pageflt/freebsd-vps-ops
import sys
from json import dumps
from argparse import ArgumentParser
from subprocess import check_output
from collections import namedtuple
hosts = {}
groups = {
"jails": {
"hosts": [],
"vars": {
"ansible_python_interpreter": "/usr/local/bin/python2.7",
}
}
}
def compile_inventory():
# Compile an inventory of running jails by quering jls(8).
try:
Jail = namedtuple('Jail', 'jid ip_address hostname path'.split())
for j in check_output(['jls']).split("\n")[1:-1]:
jail = Jail(*j.split())
groups['jails']['hosts'].append(jail.hostname)
hosts[jail.hostname] = { 'ansible_host': jail.ip_address }
except Exception as Ex:
raise Exception("get_jails(): %s" % Ex)
def parse_args():
# Parse command-line arguments.
try:
parser = ArgumentParser(description='Ansible dynamic inventory \
provider for FreeBSD jails')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--list", action="store_true")
group.add_argument("--host", metavar='HOST', type=str)
return parser.parse_args()
except Exception as Ex:
raise Exception("parse_args(): %s" % Ex)
def main():
try:
args = parse_args()
compile_inventory()
if args.list:
sys.stdout.write(dumps(groups))
else:
sys.stdout.write(dumps(hosts[args.host]) if args.host in hosts
else "{}")
return 0
except Exception as Ex:
sys.stderr.write("error: %s" % Ex)
return 1
if __name__ == "__main__":
sys.exit(main())