1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3# 4# openvz.py 5# 6# Copyright 2014 jordonr <jordon@beamsyn.net> 7# 8# This file is part of Ansible. 9# 10# Ansible is free software: you can redistribute it and/or modify 11# it under the terms of the GNU General Public License as published by 12# the Free Software Foundation, either version 3 of the License, or 13# (at your option) any later version. 14# 15# Ansible is distributed in the hope that it will be useful, 16# but WITHOUT ANY WARRANTY; without even the implied warranty of 17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18# GNU General Public License for more details. 19# 20# You should have received a copy of the GNU General Public License 21# along with Ansible. If not, see <http://www.gnu.org/licenses/>. 22# 23# Inspired by libvirt_lxc.py inventory script 24# https://github.com/ansible/ansible/blob/e5ef0eca03cbb6c8950c06dc50d0ca22aa8902f4/plugins/inventory/libvirt_lxc.py 25# 26# Groups are determined by the description field of openvz guests 27# multiple groups can be separated by commas: webserver,dbserver 28 29from subprocess import Popen, PIPE 30import sys 31import json 32 33 34# List openvz hosts 35vzhosts = ['vzhost1', 'vzhost2', 'vzhost3'] 36# Add openvz hosts to the inventory and Add "_meta" trick 37inventory = {'vzhosts': {'hosts': vzhosts}, '_meta': {'hostvars': {}}} 38# default group, when description not defined 39default_group = ['vzguest'] 40 41 42def get_guests(): 43 # Loop through vzhosts 44 for h in vzhosts: 45 # SSH to vzhost and get the list of guests in json 46 pipe = Popen(['ssh', h, 'vzlist', '-j'], stdout=PIPE, universal_newlines=True) 47 48 # Load Json info of guests 49 json_data = json.loads(pipe.stdout.read()) 50 51 # loop through guests 52 for j in json_data: 53 # Add information to host vars 54 inventory['_meta']['hostvars'][j['hostname']] = { 55 'ctid': j['ctid'], 56 'veid': j['veid'], 57 'vpsid': j['vpsid'], 58 'private_path': j['private'], 59 'root_path': j['root'], 60 'ip': j['ip'] 61 } 62 63 # determine group from guest description 64 if j['description'] is not None: 65 groups = j['description'].split(",") 66 else: 67 groups = default_group 68 69 # add guest to inventory 70 for g in groups: 71 if g not in inventory: 72 inventory[g] = {'hosts': []} 73 74 inventory[g]['hosts'].append(j['hostname']) 75 76 return inventory 77 78 79if len(sys.argv) == 2 and sys.argv[1] == '--list': 80 inv_json = get_guests() 81 print(json.dumps(inv_json, sort_keys=True)) 82elif len(sys.argv) == 3 and sys.argv[1] == '--host': 83 print(json.dumps({})) 84else: 85 print("Need an argument, either --list or --host <host>") 86