###类似K8S的编排职能,使Vmware具备自动扩容、弹性扩展为目的(通过监控回调触发弹性扩展,线上环境接入了硬件负载均衡,自动克隆出来的主机可以自动加入负载。vSphere 6.7的企业增强版本提供Instant Clone 技术,参考地址https://www.virtuallyghetto.com/2018/04/new-instant-clone-architecture-in-vsphere-6-7-part-1.html,可以秒级创建VM)。今天介绍的是VMWARE修改硬件(网卡),虚拟机克隆,预设主机名(LINUX HOSTNAME),预设IP地址等。先上一张效果图:

image.png

#一、 环境准备

  • pyvmovi 对应你的python版本,下载地址https://github.com/vmware/pyvmomi/releases
  • 保证python环境大于2.7.11

#二、克隆后预设IP和主机名

Vm克隆的 Linux 所以需要更改这几项:操作系统物理地址(/etc/udev/rules.d/70-persistent-net.rules)、IP地址、主机名,然后删除网卡中的UUID和物理地址HWADDR(这两行在Linux重启之后,操作系统会自动生成的)

使用的Vmware的CustomizationSpec(自定义规范定义)在克隆Vm后,可在不开机的情况下直接修改Vm机器的IP地址和Hostname,免去了一些繁琐的手工步骤:
代码如下:

 def ip_assign(self, vm, vm_ip, vm_gateway, vm_name):
        """设置静态IP """
        adaptermap = vim.vm.customization.AdapterMapping()
        globalip = vim.vm.customization.GlobalIPSettings()
        adaptermap.adapter = vim.vm.customization.IPSettings()
        adaptermap.adapter.ip = vim.vm.customization.FixedIp()
        adaptermap.adapter.ip.ipAddress = vm_ip
        adaptermap.adapter.subnetMask = self.subnet
        adaptermap.adapter.gateway = vm_gateway
        adaptermap.adapter.dnsDomain = self.domain
        """设置主机名"""
        ident = vim.vm.customization.LinuxPrep()
        ident.domain = self.domain
        ident.hostName = vim.vm.customization.FixedName()
        ident.hostName.name = vm_name
        customspec = vim.vm.customization.Specification()
        customspec.nicSettingMap = [adaptermap]
        customspec.globalIPSettings = globalip
        customspec.identity = ident
        print "Reconfiguring VM Networks . . ."
        task = self.get_obj([vim.VirtualMachine],vm).Customize(spec=customspec)
        self.wait_for_task(task, "config task")

 def vm_from_clone(self,src_vm_name,datastore_name,cluster_name,vm_name):
        """克隆虚拟机"""
        src_vm_name = src_vm_name
        datacenter_name = 'GQTZY'
        vm_folder = None
        datastore_name = datastore_name
        cluster_name = cluster_name
        resource_pool = None
        power_on = False
        datastorecluster_name = None
        vm_name = vm_name
        src_vm = self.get_obj( [vim.VirtualMachine], src_vm_name)
        datacenter = self.get_obj( [vim.Datacenter], datacenter_name)
        if vm_folder:
            destfolder = self.get_obj( [vim.Folder], vm_folder)
        else:
            destfolder = datacenter.vmFolder
        if datastore_name:
            datastore = self.get_obj( [vim.Datastore], datastore_name)
        else:
            datastore = self.get_obj( [vim.Datastore], src_vm.datastore[0].info.name)
        cluster = self.get_obj( [vim.ClusterComputeResource], cluster_name)
        if resource_pool:
            resource_pool = self.get_obj( [vim.ResourcePool], resource_pool)
        else:
            resource_pool = cluster.resourcePool
        vmconf = vim.vm.ConfigSpec()
        if datastorecluster_name:
            podsel = vim.storageDrs.PodSelectionSpec()
            pod = self.get_obj( [vim.StoragePod], datastorecluster_name)
            podsel.storagePod = pod
            storagespec = vim.storageDrs.StoragePlacementSpec()
            storagespec.podSelectionSpec = podsel
            storagespec.type = 'create'
            storagespec.folder = destfolder
            storagespec.resourcePool = resource_pool
            storagespec.configSpec = vmconf
            try:
                rec = self.content.storageResourceManager.RecommendDatastores(
                    storageSpec=storagespec)
                rec_action = rec.recommendations[0].action[0]
                real_datastore_name = rec_action.destination.name
            except:
                real_datastore_name = src_vm.datastore[0].info.name
            datastore = self.get_obj( [vim.Datastore], real_datastore_name)
        relospec = vim.vm.RelocateSpec()
        relospec.datastore = datastore
        relospec.pool = resource_pool
        clonespec = vim.vm.CloneSpec()
        clonespec.location = relospec
        clonespec.powerOn = power_on
        task = src_vm.Clone(folder=destfolder, name=vm_name, spec=clonespec)
        self.wait_for_task(task,actionName="cloning VM("+vm_name+") from VM("+src_vm_name+")...")

    def calculate_clusters_to_datasote(self, clusters_name):
        """计算所选集群中剩余空间最大的存储卷"""
        clusters_list = []
        if clusters_name == '':
            return
        else:
            listOBJ = self.get_obj([vim.ClusterComputeResource],clusters_name)
        for each in listOBJ.datastore:
            clusters_dict = {}
            clusters_dict[int(each.summary.freeSpace)] = each
            clusters_list.append(clusters_dict)
        return max(clusters_list)

    def get_clusters_resourcepool_dict(self):
        """获取集群和资源池对应字典"""
        clusters_resourcepool_dict = {}
        for i in self.list_obj([vim.ClusterComputeResource]):
            clusters_resourcepool_dict[i.resourcePool] = i.name
        return clusters_resourcepool_dict

后端因为设置IP和Hostname动作往往配合这Vm的克隆,而因为Vm克隆时间较长,所以这里我采用了Celery来做异步的任务处理。克隆需要传入源Vm名字,存储空间名字(自动计算集群内最大的存储空间或者手动选择),集群名字,目标Vm名字。

@task(base=MyTask)
def vm_clone(src_vm_name,vm_name,vm_get_datastore_type):
    ss = VCenter()
    ss.connect_to_vcenter()
    if vm_get_datastore_type == "1":
        """获取集群与资源池字典"""
        dict = ss.get_clusters_resourcepool_dict()
        """通过资源池获取集群名字"""
        vm_cluster_name = dict[ss.get_hosts(src_vm_name).resourcePool]
        """计算集群中最大空间存储"""
        vm_datastore_name = str(ss.calculate_clusters_to_datasote(vm_cluster_name).values()[0]).strip("''")
    elif vm_get_datastore_type == "2":
        vm_datastore_name = ss.get_hosts(src_vm_name).datastore[0]
    ss.vm_from_clone(src_vm_name, vm_datastore_name, vm_cluster_name, vm_name)