我可以使用pyvmomi将VM从一个集群克隆到另一个集群吗?

时间:2014-08-07 22:39:53

标签: python vmware

我们有两个VMware数据中心,都连接到我们的vCenter服务器。所有VMware 5.5。我有一个VM(不是模板),我想用pyvmomi以自动方式克隆。如果我指定将VM克隆到与源VM相同的数据中心中的主机,则该脚本可以正常工作。但是,如果我在另一个数据中心中指定主机,则克隆会因vmodl错误而失败:

指定的参数不正确。

据我所知,我在RelocateSpec和CloneSpec中设置了一切,以及实际的CloneVM_Task调用。我们将非常感谢任何正确方向的指针。感谢。

这是脚本:

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import atexit
import sys
import time
import pprint
#import pudb

pp = pprint.PrettyPrinter(indent=4)

def WaitForTasks(tasks, si):
    global pp
    """
    Given the service instance si and tasks, it returns after all the
    tasks are complete
    """
    pc = si.content.propertyCollector
    task_result = None
    taskList = [str(task) for task in tasks]

    # Create filter
    objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks]
    propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task, pathSet=[], all=True)
    filterSpec = vmodl.query.PropertyCollector.FilterSpec()
    filterSpec.objectSet = objSpecs
    filterSpec.propSet = [propSpec]
    filter = pc.CreateFilter(filterSpec, True)

    try:
        version, state = None, None

        # Loop looking for updates till the state moves to a completed state.
        while len(taskList):
            update = pc.WaitForUpdates(version)
            for filterSet in update.filterSet:
                for objSet in filterSet.objectSet:
                    task = objSet.obj
                    for change in objSet.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue

                        if not str(task) in taskList:
                            continue

                        if state == vim.TaskInfo.State.success:
                            #save info
                            task_result = task.info.result

                            # Remove task from taskList
                            taskList.remove(str(task))
                        elif state == vim.TaskInfo.State.error:
                            raise task.info.error
            # Move to next version
            version = update.version
    except Exception, e:
        print "Caught Exception in WaitForTasks : " + pp.pprint(e)
    finally:
        if filter:
            filter.Destroy()

    return task_result



"""
 Get the vsphere object associated with a given text name
"""
def GetObject(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            obj = c
            break
    return obj 


def WaitForIP(target_machine):
    while target_machine.guest.ipAddress == None:
        print "Waiting for IP to be visible..."
        sys.stdout.flush()
        time.sleep(1)


def main():
    global pp

    try:
        si = None
        server = 'vcenter'

        try:
            si = SmartConnect(host=server, user='adminuser', pwd='password', port=443)
        except IOError, e:
            pass
        if not si:
            print "Could not connect to vCenter using specified username and password"
            return -1

        atexit.register(Disconnect, si)

        # Get references to the needed objects
        content = si.content
        source_machine = GetObject(content,[vim.VirtualMachine],'ubuntu14.04')
        destination_host = GetObject(content, [vim.HostSystem], 'vmhostname')

        if "bos" in destination_host.name:
            dsname = 'bosdatastore'
            dcname = 'Boston'
        else:
            dsname = 'reddatastore'
            dcname = 'Redmond'

        # Configure where the new machine is to be located
        rs = vim.VirtualMachineRelocateSpec()
        cs = vim.VirtualMachineCloneSpec()
        dc = GetObject(content, [vim.Datacenter], dsname)
        target_folder = dc.vmFolder
        rs.host = destination_host
        cs.location = rs
        cs.powerOn = False

        # Clone it
        tasks = [source_machine.CloneVM_Task(target_folder, 'newmachine', cs)]
        print "Clone initiated..."
        sys.stdout.flush()
        target_machine = WaitForTasks(tasks, si)
        print("Virtual Machine %s has been cloned successfully" % "newmachine")

        # update NIC settings if needed
        for dev in target_machine.config.hardware.device:
            if dev.deviceInfo.label == 'Network adapter 1':
                nic = dev
                break

        if nic.backing.deviceName != 'vlan1':
            net = GetObject(content,[vim.Network],'vlan2')
            vds = vim.vm.device.VirtualDeviceSpec()
            nic.backing.deviceName = 'vlan2'
            nic.backing.network = net
            nic.deviceInfo.summary = 'vlan2'
            vds.device = nic
            vds.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
            vmcs = vim.vm.ConfigSpec()
            vmcs.deviceChange = [vds]
            tasks = [target_machine.ReconfigVM_Task(vmcs)]
            print "Network change started..."
            sys.stdout.flush()
            WaitForTasks(tasks,si)
            print "Network update complete."

        # Power the machine on
        tasks = [target_machine.PowerOnVM_Task()]
        print "New machine is starting..."
        sys.stdout.flush()
        WaitForTasks(tasks,si)

        # Wait for target to have IP so we can save it
        WaitForIP(target_machine)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault in main : " + pp.pprint(e)
    except Exception, e:
        print "Caught Exception in main : " + pp.pprint(e)

    print "Done."

# Start program
if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

CloneSpec采用参数RelocateSpec。所以基本上你是克隆虚拟机/模板并迁移(我不知道它是热还是冷)它到不同的主机/集群。

在看到你的问题后,我用Google搜索的第一件事就是" vMotion可以在数据中心之间进行,也可以不进行"。我得到了答案," vMotion不可能跨数据中心,但可以进行冷迁移"

现在正如我所说,我不知道RelocateSpec是否使用vMotion。但看起来即使每个数据中心的所有主机共享一个共同的回购也不可能。

从Vmware查看本文Cloning VM from one datacenter to another datacenter。它基本上克隆并将其导出为ovf,然后在目标数据中心中导入ovf。