【问题标题】:Can I clone a VM from one cluster to another using pyvmomi?我可以使用 pyvmomi 将 VM 从一个集群克隆到另一个集群吗?
【发布时间】:2014-08-07 22:39:52
【问题描述】:

我们有两个 VMware 数据中心,都连接到我们的 vCenter 服务器。所有 VMware 5.5。我有一个虚拟机(不是模板),我想使用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()

【问题讨论】:

  • 您似乎错过了在此行adminuser 用户名si = SmartConnect(host=server, user='adminuser, pwd='password', port=443) 之后关闭报价
  • 谢谢。这是我清理脚本时出现的编辑错误。

标签: python vmware


【解决方案1】:

CloneSpec 接受一个参数 RelocateSpec 。所以基本上你正在克隆一个虚拟机/模板并将其迁移(我不知道它是热的还是冷的)它到不同的主机/集群。

看到您的问题后,我在 Google 上搜索的第一件事是“vMotion 是否可以跨数据中心”。我得到的答案是,“跨数据中心无法实现 vMotion,但可以进行冷迁移”

正如我所说,我不知道 RelocateSpec 是否使用 vMotion。但看起来即使每个数据中心的所有主机都共享一个公共存储库也是不可能的。

看看这篇来自 Vmware 的文章Cloning VM from one datacenter to another datacenter。它基本上将其克隆并导出为 ovf,然后将 ovf 导入目标数据中心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2022-07-11
    • 2016-12-07
    相关资源
    最近更新 更多