1#!/usr/local/bin/python3.8
2# -*- coding: utf-8 -*-
3#
4# openvz.py
5#
6# Copyright 2014 jordonr <jordon@beamsyn.net>
7# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8#
9# Inspired by libvirt_lxc.py inventory script
10# https://github.com/ansible/ansible/blob/e5ef0eca03cbb6c8950c06dc50d0ca22aa8902f4/plugins/inventory/libvirt_lxc.py
11#
12# Groups are determined by the description field of openvz guests
13# multiple groups can be separated by commas: webserver,dbserver
14
15from __future__ import (absolute_import, division, print_function)
16__metaclass__ = type
17
18from subprocess import Popen, PIPE
19import sys
20import json
21
22
23# List openvz hosts
24vzhosts = ['vzhost1', 'vzhost2', 'vzhost3']
25# Add openvz hosts to the inventory and Add "_meta" trick
26inventory = {'vzhosts': {'hosts': vzhosts}, '_meta': {'hostvars': {}}}
27# default group, when description not defined
28default_group = ['vzguest']
29
30
31def get_guests():
32    # Loop through vzhosts
33    for h in vzhosts:
34        # SSH to vzhost and get the list of guests in json
35        pipe = Popen(['ssh', h, 'vzlist', '-j'], stdout=PIPE, universal_newlines=True)
36
37        # Load Json info of guests
38        json_data = json.loads(pipe.stdout.read())
39
40        # loop through guests
41        for j in json_data:
42            # Add information to host vars
43            inventory['_meta']['hostvars'][j['hostname']] = {
44                'ctid': j['ctid'],
45                'veid': j['veid'],
46                'vpsid': j['vpsid'],
47                'private_path': j['private'],
48                'root_path': j['root'],
49                'ip': j['ip']
50            }
51
52            # determine group from guest description
53            if j['description'] is not None:
54                groups = j['description'].split(",")
55            else:
56                groups = default_group
57
58            # add guest to inventory
59            for g in groups:
60                if g not in inventory:
61                    inventory[g] = {'hosts': []}
62
63                inventory[g]['hosts'].append(j['hostname'])
64
65        return inventory
66
67
68if len(sys.argv) == 2 and sys.argv[1] == '--list':
69    inv_json = get_guests()
70    print(json.dumps(inv_json, sort_keys=True))
71elif len(sys.argv) == 3 and sys.argv[1] == '--host':
72    print(json.dumps({}))
73else:
74    print("Need an argument, either --list or --host <host>")
75