ansible-tools/vmw_snapshot_create

104 lines
2.5 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='Creates 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 create snapshot of')
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 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 not vm:
print("vm not found")
exit(1)
description = 'vmw_snapshot_create'
dump_memory = True
quiesce = False
wait_for_task(vm.CreateSnapshot(
args.snapshotname, description, dump_memory, quiesce
))
if __name__ == "__main__":
main()
# vim: set tabstop=4 shiftwidth=4 expandtab smarttab: