pythonでvSphere操作　その8　VMスナップショット削除・作成・リストアップ

#本題
スナップショットのリストアップ、作成、削除の操作。

```python:manage_snapshot.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
from getpass import getpass

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

def set_args():
    p = argparse.ArgumentParser(
             description='create, list, delete snapshots.')
    s = p.add_subparsers(help='sub-command help', dest='subparser_name')

    c = s.add_parser('create', help='create snaps')
    d = s.add_parser('delete', help='delete snaps')
    l = s.add_parser('list', help='list snapshot list')

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

    c.add_argument('-d', '--snapdescription',
                   required=False,
                   default='default snapshot descreption',
                   action='store',
                   help='specify description of snapshot')

    d.add_argument('-s', '--snapshot',
                   required=True,
                   action='store',
                   help='spececify snapshotname to delete')

    args = p.parse_args()
    return args

def main():
    args = set_args()

    #interactions
    def _chkinput(name):
        a = raw_input(name + ': ')
        if not bool(a):
            print 'error:empty value'
            sys.exit(1)
        else:
            return a

    print 'Enter login information below for Vcenter access.'
    h = _chkinput('vCenterIP')
    u = _chkinput('User')
    p = getpass(prompt='Password(shadowed): ')
    t = raw_input('Port(if empty,default(443) is used): ')
    if not bool(t):
        t = 443

    #make connection
    si = SmartConnectNoSSL(host=h,
                           user=u,
                           pwd=p,
                           port=t)

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

    #fetch vminfo
    print 'Enter vmname you wish to operate.'
    vm = _chkinput('vmname')
    content = si.RetrieveContent()
    vm_obj = content.searchIndex.FindByDnsName(None,
                                               vm,
                                               vmSearch=True)

    if not 'create' in args.subparser_name:
        if not hasattr(vm_obj.snapshot, 'rootSnapshotList'):
            print time() + 'snapshot does not exists.'
            sys.exit(2)
    else:
        pass

    if 'create' in args.subparser_name:
        #take snapshot
        print time() + 'start snap operation...'
        task = vm_obj.CreateSnapshot_Task(name=args.snapname,
                                            description=args.snapdescription,
                                            memory=True,
                                            quiesce=True)
        if WaitForTask(task):
            print time() + 'finish snap operation.'

    elif 'delete' in args.subparser_name:
        #delete snapshot
        snaplist_obj = vm_obj.snapshot.rootSnapshotList
        if args.snapshot == snaplist_obj[0].name:
            snap_obj = snaplist_obj[0].snapshot
        else:
            while hasattr(snaplist_obj[0], 'childSnapshotList'):
                if args.snapshot == snaplist_obj[0].childSnapshotList[0].name:
                    snap_obj = snaplist_obj[0].childSnapshotList[0].snapshot
                    break
                else:
                    snaplist_obj = snaplist_obj[0].childSnapshotList


        print time() + 'deleting snashot...'
        task = snap_obj.RemoveSnapshot_Task(True)
        if WaitForTask(task):
            print time() + 'finish operation.'

    elif 'list' in args.subparser_name:
        #list snaps
        snaplist_obj = vm_obj.snapshot.rootSnapshotList
        print time() + 'listing snapshot below...'
        cdate = '{0:%Y-%m-%d %H:%M:%S}'.format(snaplist_obj[0].createTime)
        sname = snaplist_obj[0].name
        print 'Created : [' + cdate + '] ' + 'snapshot name : [' + sname + ']'
        try:
            while hasattr(snaplist_obj[0], 'childSnapshotList'):
                cdate = '{0:%Y-%m-%d %H:%M:%S}'.format(snaplist_obj[0].childSnapshotList[0].createTime)
                sname = snaplist_obj[0].childSnapshotList[0].name
                print 'Created : [' + cdate + '] ' + 'snapshot name : [' + sname + ']'
                snaplist_obj = snaplist_obj[0].childSnapshotList
        except:
            None

if __name__ == "__main__":
    main()
```

#ポイント
・サブパーサーで処理を区分する。
・ログイン情報はraw_inputから持ってくる。
・スナップショットを再帰的に見る(削除・リストアップ処理)。