111 lines
2.9 KiB
Python
Executable File
111 lines
2.9 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='Reads vm names from stdin, removes all snapshots.')
|
|
|
|
parser.add_argument('-s', '--site',
|
|
required=True,
|
|
action='store',
|
|
help='name of the site to connect to')
|
|
|
|
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 snapshots(snaplist, depth=0):
|
|
snapshot_data = []
|
|
for s in snaplist:
|
|
text = ". " * depth + "(%s) %s / %s" % (s.state, s.name, s.createTime)
|
|
snapshot_data.append(text)
|
|
snapshot_data = snapshot_data + snapshots(s.childSnapshotList, depth + 1)
|
|
return snapshot_data
|
|
|
|
|
|
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.SmartConnectNoSSL(
|
|
host = host,
|
|
user = user,
|
|
pwd = passwd
|
|
)
|
|
atexit.register(pyVim.connect.Disconnect, si)
|
|
content = si.RetrieveContent()
|
|
|
|
while True:
|
|
vmname = sys.stdin.readline()
|
|
if vmname == '': break # EOF
|
|
vmname = vmname.rstrip()
|
|
if vmname == '': continue # empty line
|
|
vm = get_obj(content, [vim.VirtualMachine], vmname)
|
|
if vm == None:
|
|
print("vm not found: "+ vmname)
|
|
continue
|
|
if vm.snapshot is None:
|
|
print("vm has no snapshots: "+ vmname)
|
|
continue
|
|
print("removing all snapshots of: "+ vmname)
|
|
snaplist = snapshots(vm.snapshot.rootSnapshotList)
|
|
for s in snaplist:
|
|
print(" "+ s)
|
|
|
|
wait_for_task(vm.RemoveAllSnapshots())
|
|
if vm.snapshot is None:
|
|
print("done.")
|
|
else:
|
|
print("warning: vm has still snapshots!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
# vim: set tabstop=4 shiftwidth=4 expandtab smarttab:
|