115 lines
3.0 KiB
Python
Executable File
115 lines
3.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
from pyVmomi import vim
|
|
import pyVim.connect
|
|
import atexit
|
|
import argparse
|
|
from pprint import pprint
|
|
import sys
|
|
import siteconf
|
|
|
|
site_conf = siteconf.read()
|
|
|
|
|
|
def get_args():
|
|
parser = argparse.ArgumentParser(
|
|
description='Deletes a vm snapshot.')
|
|
|
|
parser.add_argument('-s', '--site',
|
|
required=True,
|
|
action='store',
|
|
help='name of the site to connect to')
|
|
|
|
parser.add_argument('-v', '--vm',
|
|
required=True,
|
|
action='store',
|
|
help='vm to delete snapshot from')
|
|
|
|
parser.add_argument('-n', '--snapshotname',
|
|
required=True,
|
|
action='store',
|
|
help='snapshot name')
|
|
|
|
args = parser.parse_args()
|
|
return args
|
|
|
|
def get_obj(content, vimtype, name):
|
|
"""
|
|
Return an object by name, if name is None the
|
|
first found object is returned
|
|
"""
|
|
obj = None
|
|
container = content.viewManager.CreateContainerView(
|
|
content.rootFolder, vimtype, True)
|
|
for c in container.view:
|
|
if name:
|
|
if c.name == name:
|
|
obj = c
|
|
break
|
|
else:
|
|
obj = c
|
|
break
|
|
return obj
|
|
|
|
|
|
def wait_for_task(task):
|
|
""" wait for a vCenter task to finish """
|
|
task_done = False
|
|
while not task_done:
|
|
if task.info.state == 'success':
|
|
return task.info.result
|
|
|
|
if task.info.state == 'error':
|
|
print("there was an error")
|
|
task_done = True
|
|
|
|
|
|
def find_snapshots(snapshots, name):
|
|
snap_obj = []
|
|
for snapshot in snapshots:
|
|
if snapshot.name == name:
|
|
snap_obj.append(snapshot)
|
|
snap_obj = snap_obj + find_snapshots(
|
|
snapshot.childSnapshotList, name)
|
|
return snap_obj
|
|
|
|
|
|
def main():
|
|
args = get_args()
|
|
|
|
if not args.site in site_conf:
|
|
print(f"site not found: {args.site}")
|
|
exit(1)
|
|
host = site_conf[args.site]['vcenter']
|
|
user = site_conf[args.site]['vcenter_user']
|
|
passwd = site_conf[args.site]['vcenter_passwd']
|
|
|
|
|
|
si = pyVim.connect.SmartConnect(
|
|
host = host,
|
|
user = user,
|
|
pwd = passwd,
|
|
disableSslCertValidation = True
|
|
)
|
|
atexit.register(pyVim.connect.Disconnect, si)
|
|
content = si.RetrieveContent()
|
|
|
|
vm = get_obj(content, [vim.VirtualMachine], args.vm)
|
|
if vm == None:
|
|
print("vm not found: "+ args.vm)
|
|
exit(1)
|
|
if vm.snapshot is None:
|
|
print("vm has no snapshots: "+ args.vm)
|
|
exit(1)
|
|
snaplist = find_snapshots(vm.snapshot.rootSnapshotList, args.snapshotname)
|
|
for s in snaplist:
|
|
print(f"removing {args.vm} snapshot {s.name} ({s.createTime})")
|
|
remove_children = False
|
|
consolidate = True
|
|
wait_for_task(s.snapshot.RemoveSnapshot_Task(remove_children, consolidate))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
# vim: set tabstop=4 shiftwidth=4 expandtab smarttab:
|