api
vSphere
Snapshot
pyvmomi

pythonでvSphere操作 その7 VMスナップショット作成

本題

基礎さえ出来てしまえばあとは簡単。

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

from pyVim.connect import SmartConnectNoSSL, Disconnect
from pyVmomi import vim, vmodl
import atexit, argparse, sys
from datetime import datetime
from pyVim.task import WaitForTask

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

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 IP')

    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 login User')

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

    parser.add_argument('-m', '--vmname',
                        required=True,
                        action='store',
                        help='specify VM name to make')

    parser.add_argument('-n', '--snapname',
                        required=False,
                        default='snapshot@'+ time(),
                        action='store',
                        help='specify snapshot name')

    parser.add_argument('-d', '--snapdescription',
                        required=False,
                        default='default snapshot descreption',
                        action='store',
                        help='specify VM name to make')

    args = parser.parse_args()
    return args

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)

    #fetch vminfo
    content = si.RetrieveContent()
    vmachine = content.searchIndex.FindByDnsName(None,
                                                 args.vmname,
                                                 vmSearch=True)
    #take snapshot
    print time() + 'start snap operation'
    task = vmachine.CreateSnapshot_Task(name=args.snapname,
                                        description=args.snapdescription,
                                        memory=True,
                                        quiesce=True)
    if WaitForTask(task):
        print time() + 'finish snap operation'

if __name__ == "__main__":
    main()

searchIndexは便利。