vsphere 即时克隆


用途

vsphere6.7即以上的instant clone,使用脚本进行设置
属于能用就行的东西,不想优化

环境

conda create -n vsphere python=3.7

source activate vsphere

or

conda activate vsphere

python -m pip install -i https://mirrors.aliyun.com/pypi/simple pyvmomi

脚本

instant_clone.py

# encoding=utf-8
from common import info
import atexit
import requests.packages.urllib3 as urllib3
import ssl
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
import time
from tools import tasks
"""
 Waits and provides updates on a vSphere task
"""
def WaitTask(task, actionName='job', hideResult=True):
    #print 'Waiting for %s to complete.' % actionName  
    if task ==None:
        return 'no value'
    while task.info.state == vim.TaskInfo.State.running:
        time.sleep(1) 
    print(task.info)
    if task.info.state == vim.TaskInfo.State.success:
       if task.info.result is not None and not hideResult:
          out = '%s completed successfully, result: %s' % (actionName, task.info.result)
       else:
          out = '%s completed successfully.' % actionName
    else:
       out = '%s did not complete successfully: %s' % (actionName, task.info.error)
       print(out)
       raise task.info.error # should be a Fault... check XXX

    # may not always be applicable, but can't hurt.
    return task.info.result



def get_obj(content, vimtype, name, folder=None):
    obj = None
    if not folder:
        folder = content.rootFolder
    container = content.viewManager.CreateContainerView(folder, vimtype, True)
    for item in container.view:
        if item.name == name:
            obj = item
            break
    return obj


# 开始连接vcenter
si = None
context = None
if hasattr(ssl, 'SSLContext'):
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE
if context:
    si = SmartConnect(host=info.host, port=int(info.port), user=info.user,
                      pwd=info.password, sslContext=context)
atexit.register(Disconnect, si)
print("Connected to vCenter Server")
content = si.RetrieveContent()

# 获取datacenter
datacenter = get_obj(content, [vim.Datacenter], info.datacenter_name)
if not datacenter:
    raise Exception("Couldn't find the Datacenter with the provided name " "'{}'".format(info.datacenter_name))


def instant_clone(new_vm_name,template_name,ResourcePool='即时克隆'):
    # 获取vm
    vm_folder = datacenter.vmFolder
    vm_template = get_obj(content, [vim.VirtualMachine], template_name, vm_folder)
    if not vm_template:
        raise Exception("Couldn't find the template with the provided name "
                        "'{}'".format(template_name))
    #写定位置,这里是资源池
    InstantClone_location = vim.vm.RelocateSpec()
    InstantClone_location.pool=get_obj(content, [vim.ResourcePool], ResourcePool)
    #即时克隆参数
    InstantClonespec = vim.vm.InstantCloneSpec()
    InstantClonespec.location =  InstantClone_location
    InstantClonespec.name = new_vm_name
    #即时克隆
    InstantClone_task=vm_template.InstantClone(InstantClonespec)
    tasks.wait_for_tasks(si,[InstantClone_task])
    # new_vm = WaitTask(InstantClone_task, 'VM InstantClone task')

    #进行重启
    rebook_task=InstantClone_task.info.result.RebootGuest()
    reboot_result = WaitTask(rebook_task, 'VM Reboot task')
    print(new_vm_name,reboot_result)

    # tasks.wait_for_tasks(si,[rebook_task])
    # print(new_vm_name,'Reboot ok')


def main():
    new_vm_name_list=['123','456']
    template_name='ubuntu18.04_x64_server_base'
    ResourcePool='即时克隆'
    for new_vm_name in new_vm_name_list:
        instant_clone(new_vm_name,template_name,ResourcePool=ResourcePool)

if __name__ == "__main__":
    main()

get_infomation.py

# encoding=utf-8
from common import info
import atexit
import requests.packages.urllib3 as urllib3
import ssl
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect


def get_obj(content, vimtype, name, folder=None):
    obj = None
    infomation = []
    if not folder:
        folder = content.rootFolder
    container = content.viewManager.CreateContainerView(folder, vimtype, True)
    for item in container.view:
        infomation.append(item.name)
        if item.name == name:
            obj = item
            break
    return obj, infomation


# 开始连接vcenter
si = None
context = None
if hasattr(ssl, 'SSLContext'):
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE
if context:
    si = SmartConnect(host=info.host, port=int(info.port), user=info.user,
                      pwd=info.password, sslContext=context)
atexit.register(Disconnect, si)
print("Connected to vCenter Server")
content = si.RetrieveContent()

# 获取datacenter 信息
datacenter, datacenter_infomation = get_obj(content, [vim.Datacenter], info.datacenter_name)
print("datacenter :", datacenter_infomation)
if not datacenter:
    raise Exception("Couldn't find the Datacenter with the provided name " "'{}'".format(info.datacenter_name))

# 获取cluster信息
cluster, cluster_infomation = get_obj(content, [vim.ComputeResource], info.cluster_name, datacenter.hostFolder)
print('cluster_name : ', cluster_infomation)

# 获取资源池信息
ResourcePool, ResourcePool_infomation = get_obj(content, [vim.ResourcePool], info.template_name)
print('ResourcePool : ', ResourcePool_infomation)

# 获取vm信息
vm_folder = datacenter.vmFolder
vm, vm_infomation = get_obj(content, [vim.VirtualMachine], info.template_name, vm_folder)
print('vm : ', vm_infomation)

文章作者: xyzz
文章链接: http://www.xyzzpwn.top
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xyzz !
 上一篇
git清空所有记录 git清空所有记录
git的一些操作清空所有commitgit checkout --orphan latest_branch; git add -A; git commit -m "commit message"; git branch
2020-08-14
下一篇 
nextcloud nextcloud
sudo yum install -y yum-utils device-mapper-persistent-data lvm2; sudo yum-config-manager --add-repo https://download.d
2019-09-26
  目录