def cloneToTemplate(VM, dstFolder, dstDatastore): backup_snapshot = takeSnapshot(VM) if not (backup_snapshot): logging.warning("Error taking snapshot of virtual machine \"" + VM.name + "\"") return None else: spec = vim.VirtualMachineCloneSpec() location = vim.VirtualMachineRelocateSpec() location.folder = dstFolder location.datastore = dstDatastore spec.location = location spec.snapshot = backup_snapshot spec.template = True spec.memory = False task = VM.CloneVM_Task(name=VM.name + "_Backup_" + (datetime.today()).strftime("%Y-%m-%d_%H-%M"), spec=spec, folder=dstFolder) if trackTask(task): logging.info("Successfull backup of VM " + VM.name + ", deleting Snapshot") deleteSnapshot(backup_snapshot) deleteOldBackups(VM, 2, dstFolder) else: logging.warning("Something gone wrong with coping VM \"" + VM.name + "\". Deleting made snapshot.") deleteSnapshot(backup_snapshot)
def DeployVmFn(Properties): task = Properties['task'] params = getParameters(task['Parameters']) opStatus = {} # =========================================================================== # Connect to Vcenter # =========================================================================== si = connectVcenter(Properties) obj = getObjRef(si.content, vim.VirtualMachine, params['Template']) destination_host = getObjRef(si.content, vim.HostSystem, params['Host']) dc = getObjRef(si.content, vim.Datacenter, params['Datacenter']) cluster = getObjRef(si.content, vim.ClusterComputeResource, params['Cluster']) if obj is None: msg = "A object named " + params['Template'] + " could not be found" updateFailedTaskList(task['TaskName'], params, msg, opStatus) elif destination_host is None: msg = "A object named " + params['Host'] + " could not be found" updateFailedTaskList(task['TaskName'], params, msg, opStatus) elif dc is None: msg = "A object named " + params['Datacenter'] + " could not be found" updateFailedTaskList(task['TaskName'], params, msg, opStatus) elif cluster is None: msg = "A object named " + params['Cluster'] + " could not be found" updateFailedTaskList(task['TaskName'], params, msg, opStatus) else: try: print(" Deploying the VM %s" % obj.name) rs = vim.VirtualMachineRelocateSpec() cs = vim.VirtualMachineCloneSpec() target_folder = dc.vmFolder rs.host = destination_host rs.pool = cluster.resourcePool cs.location = rs cs.powerOn = False print ("Deploy initiated...") WaitForTask(obj.CloneVM_Task(target_folder, params['VmName'], cs)) print(" Virtual Machine %s has been Deployed successfully" % params['VmName']) opStatus['ObjectName'] = getObjName(obj) opStatus['Status'] = 'Passed' except Exception as e: updateFailedTaskList(task['TaskName'], params, e.msg, opStatus) # =========================================================================== # Disconnect Vcenter # =========================================================================== Disconnect(si) return opStatus
def clone( content, template, name, pool, folder, datastore, ): vm_mor = get_object(content, vim.VirtualMachine, template) if vm_mor is None: logger.error(u'VirtualMachine %s not found' % template) return None pool_mor = get_object(content, vim.ResourcePool, pool) if pool_mor is None: logger.error(u'ResourcePoll %s not found' % pool) return None folder_mor = get_object(content, vim.Folder, folder) if folder_mor is None: loggeer.error(u'Folder %s not found' % folder) return None datastore_mor = get_object(content, vim.Datastore, datastore) if datastore_mor is None: logger.error(u'Datastore %s not found' % datastore) return None r_spec = vim.VirtualMachineRelocateSpec() c_spec = vim.VirtualMachineCloneSpec() r_spec.pool = pool_mor r_spec.datastore = datastore_mor c_spec.location = r_spec c_spec.powerOn = True # TODO: zvazit alternativne riesenie cez metodu vm_mor.Clone return vm_mor.CloneVM_Task(name=name, folder=folder_mor, spec=c_spec)
def _clone(self, destination, resourcepool=None, datastore=None, power_on=True, sparse=False, template=False, provision_timeout=1800, progress_callback=None, allowed_datastores=None, cpu=None, ram=None, **kwargs): """ Clone this template to a VM Returns a VMWareVirtualMachine object """ try: vm = self.system.get_vm(destination) except VMInstanceNotFound: vm = None if vm: raise Exception("VM/template of the name {} already present!".format(destination)) if progress_callback is None: progress_callback = partial( self._progress_log_callback, self.logger, self.name, destination) source_template = self.raw vm_clone_spec = vim.VirtualMachineCloneSpec() vm_reloc_spec = vim.VirtualMachineRelocateSpec() # DATASTORE if isinstance(datastore, six.string_types): vm_reloc_spec.datastore = self.system.get_obj(vim.Datastore, name=datastore) elif isinstance(datastore, vim.Datastore): vm_reloc_spec.datastore = datastore elif datastore is None: if allowed_datastores is not None: # Pick a datastore by space vm_reloc_spec.datastore = self._pick_datastore(allowed_datastores) else: # Use the same datastore datastores = source_template.datastore if isinstance(datastores, (list, tuple)): vm_reloc_spec.datastore = datastores[0] else: vm_reloc_spec.datastore = datastores else: raise NotImplementedError("{} not supported for datastore".format(datastore)) progress_callback("Picked datastore `{}`".format(vm_reloc_spec.datastore.name)) # RESOURCE POOL if isinstance(resourcepool, vim.ResourcePool): vm_reloc_spec.pool = resourcepool else: vm_reloc_spec.pool = self._get_resource_pool(resourcepool) progress_callback("Picked resource pool `{}`".format(vm_reloc_spec.pool.name)) vm_reloc_spec.host = None if sparse: vm_reloc_spec.transform = vim.VirtualMachineRelocateTransformation().sparse else: vm_reloc_spec.transform = vim.VirtualMachineRelocateTransformation().flat vm_clone_spec.powerOn = power_on vm_clone_spec.template = template vm_clone_spec.location = vm_reloc_spec vm_clone_spec.snapshot = None if cpu is not None: vm_clone_spec.config.numCPUs = int(cpu) if ram is not None: vm_clone_spec.config.memoryMB = int(ram) try: folder = source_template.parent.parent.vmParent except AttributeError: folder = source_template.parent progress_callback("Picked folder `{}`".format(folder.name)) task = source_template.CloneVM_Task(folder=folder, name=destination, spec=vm_clone_spec) def _check(store=[task]): try: if hasattr(store[0].info, 'progress') and store[0].info.progress is not None: progress_callback("{}/{}%".format(store[0].info.state, store[0].info.progress)) else: progress_callback("{}".format(store[0].info.state)) except AttributeError: pass if store[0].info.state not in {"queued", "running"}: return True store[0] = self.system.get_updated_obj(store[0]) return False wait_for(_check, num_sec=provision_timeout, delay=4) if task.info.state != 'success': self.logger.error( "Clone VM from VM/template '%s' failed: %s", self.name, get_task_error_message(task) ) raise VMInstanceNotCloned(destination) if template: entity_cls = VMWareTemplate else: entity_cls = VMWareVirtualMachine return entity_cls(system=self.system, name=destination)