LoginSignup
1
0

More than 5 years have passed since last update.

pythonでvSphere操作 その5 VM有無確認

Last updated at Posted at 2018-04-03

本題

VMが存在するかのチェックをする。

py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pyVim.connect import SmartConnectNoSSL, Disconnect
from pyVmomi import vim
import atexit
import argparse
import sys

args = None

#time
def time():
    d = datetime.today().strftime("%Y-%m-%d %H:%M:%S") + " "
    return d

#set arguments
def set_args():
    parser = argparse.ArgumentParser(
             description='required arguments for retreiving infos from vcenter.')

    parser.add_argument('-s', '--host',
                        required=True,
                        action='store',
                        help='specify vCenter name')

    parser.add_argument('-o', '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='specify port')

    parser.add_argument('-u', '--user',
                        required=True,
                        action='store',
                        help='specify User name')

    parser.add_argument('-p', '--password',
                        required=True,
                        action='store',
                        help='specify Password')

    parser.add_argument('-q', '--queryname',
                        required=True,
                        action='store',
                        help='specify vmname to query')

    global args
    args = parser.parse_args()
    return args


def searcher(vm):
    vname = vm.summary.config.name
    if vname == args.queryname:
        print time() + args.queryname + " alreadyexits"
        sys.exit(1)
    else:
        pass


def main():
    #make connection
    args = set_args()
    si = SmartConnectNoSSL(host=args.host,
                           user=args.user,
                           pwd=args.password,
                           port=args.port)

    #set action at the end
    atexit.register(Disconnect, si)

    #create container
    content = si.RetrieveContent()
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True
    containerView = content.viewManager.CreateContainerView(
                    container, viewType, recursive)

    #search
    children = containerView.view
    for child in children:
        searcher(child)

    print time() + "set " + args.queryname + " to be created."

if __name__ == "__main__":
    main()

とりあえずargparse部分は置いておいて、肝となる部分。

py
 #create container
    content = si.RetrieveContent()
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True
    containerView = content.viewManager.CreateContainerView(
                    container, viewType, recursive)

    #search
    children = containerView.view
    for child in children:
        searcher(child)

VMのMOにはルールがあるらしい。

ServiceInstance(MO)→ServiceContent(DataObject、以下DO)→...
という風に、ServiceInstanceの次に必ずServiceContentを作成してから、各種操作をする。

content = si.RetrieveContent()はServiceInstance用のServiceContentを作成。
content.viewManager.CreateContainerViewはServiceContentのviewManager(MO)を呼び出してCreateContainerViewメソッドで条件を指定してContainerView(MO)を作成する。

下記がその条件。詳しくはVMのドキュメント参照。
container = content.rootFolder  #rootフォルダを見る。ServiceContentのプロパティ
viewType = [vim.VirtualMachine] #VM情報を指定。vim.VirtualMachineはMO
recursive = True          #再帰的にフォルダをみるよ。

故にContainerViewにVM情報が含まれる。
viewメソッドでcontainerViewを見て、argparserで取得したVM名をfor文で回して一致するものがあるか確認している。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0