You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java API基于VMware vCenter虚拟机模板批量创建虚拟机?

Deploying VMs from a vCenter Template Using VMware vSphere Java SDK (Batch Example)

Got it, I’ve tackled this exact scenario before—here’s a complete, working code example to batch-create VMs from an existing vCenter template using the vSphere Java SDK, plus key details to make sure it works smoothly for you.

Prerequisites

First, make sure you have the vSphere Java SDK dependency set up. If you’re using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.vmware</groupId>
    <artifactId>vsphere-client-sdk</artifactId>
    <version>7.0.3</version> <!-- Use the version matching your vCenter -->
</dependency>

You’ll also need:

  • A valid vCenter connection (already authenticated, using VimService/VimPortType)
  • The Managed Object Reference (MoRef) of your target template
  • MoRefs for your target resource pool, folder, and datastore (or datastore cluster)

Batch Deployment Code Example

Here’s a full, annotated code snippet that handles batch cloning:

import com.vmware.vim25.*;
import java.util.ArrayList;
import java.util.List;

public class VmTemplateCloner {
    private final VimPortType vimPort;
    private final ServiceContent serviceContent;

    // Initialize with your existing vCenter connection
    public VmTemplateCloner(VimPortType vimPort, ServiceContent serviceContent) {
        this.vimPort = vimPort;
        this.serviceContent = serviceContent;
    }

    public void batchCloneFromTemplate(
            ManagedObjectReference templateRef,
            ManagedObjectReference targetFolderRef,
            ManagedObjectReference targetResourcePoolRef,
            List<String> vmNames,
            int numberOfCpus,
            long memoryMb
    ) throws Exception {
        // Create a base clone spec - we'll reuse this with per-VM tweaks
        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
        cloneSpec.setPowerOn(true); // Power on the VM after cloning
        cloneSpec.setTemplate(false); // Make sure the result is a VM, not a template

        // Configure VM hardware (optional - matches template if not set)
        VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
        configSpec.setNumCPUs(numberOfCpus);
        configSpec.setMemoryMB(memoryMb);
        cloneSpec.setConfig(configSpec);

        // Optional: Add customization (e.g., set hostname, IP)
        // Uncomment and customize if you need unique guest OS settings
        /*
        CustomizationSpec customizationSpec = createCustomizationSpec();
        cloneSpec.setCustomization(customizationSpec);
        */

        // Batch process each VM name
        List<TaskInfo> taskInfos = new ArrayList<>();
        for (String vmName : vmNames) {
            System.out.printf("Starting clone for VM: %s%n", vmName);
            
            // Clone the template - this is the key method (not createVM)
            ManagedObjectReference taskRef = vimPort.cloneVM_Task(
                    templateRef,
                    targetFolderRef,
                    vmName,
                    cloneSpec,
                    targetResourcePoolRef,
                    null // Use default host/datastore from resource pool
            );

            // Wait for the task to complete (or collect tasks to process asynchronously)
            TaskInfo taskInfo = waitForTask(taskRef);
            taskInfos.add(taskInfo);
            System.out.printf("Clone completed for VM: %s (Status: %s)%n", vmName, taskInfo.getState());
        }
    }

    // Helper to wait for a vCenter task to finish
    private TaskInfo waitForTask(ManagedObjectReference taskRef) throws Exception {
        TaskInfo taskInfo;
        do {
            Thread.sleep(1000); // Poll every second
            taskInfo = (TaskInfo) vimPort.retrievePropertiesEx(
                    serviceContent.getPropertyCollector(),
                    new RetrieveOptions(),
                    new PropertyFilterSpec[] {
                            new PropertyFilterSpec(
                                    new ObjectSpec[]{new ObjectSpec(taskRef)},
                                    new PropertySpec[]{new PropertySpec(Task.class, new String[]{"info"}, null, true)}
                            )
                    }
            ).getObjects().get(0).getPropSet().get(0).getVal();
        } while (taskInfo.getState() == TaskInfoState.RUNNING || taskInfo.getState() == TaskInfoState.QUEUED);

        return taskInfo;
    }

    // Optional: Create a customization spec for guest OS settings
    private CustomizationSpec createCustomizationSpec() {
        CustomizationSpec spec = new CustomizationSpec();
        spec.setDomain("your-domain.com");
        spec.setFullName("VM Admin");
        spec.setOrgName("Your Org");

        // Set hostname (use a unique value per VM if needed)
        CustomizationFixedName name = new CustomizationFixedName();
        name.setName("custom-vm-hostname");
        CustomizationGlobalIPSettings globalSettings = new CustomizationGlobalIPSettings();
        spec.setGlobalIPSettings(globalSettings);
        CustomizationIdentification id = new CustomizationIdentification();
        id.setHostName(name);
        spec.setIdentification(id);

        return spec;
    }

    // Example usage
    public static void main(String[] args) throws Exception {
        // Assume you've already set up your vCenter connection here
        // VimPortType vimPort = ...;
        // ServiceContent serviceContent = ...;
        // ManagedObjectReference templateRef = ...; // Get your template's MoRef
        // ManagedObjectReference targetFolderRef = ...;
        // ManagedObjectReference targetResourcePoolRef = ...;

        List<String> vmNames = List.of("VM-Batch-01", "VM-Batch-02", "VM-Batch-03");
        VmTemplateCloner cloner = new VmTemplateCloner(vimPort, serviceContent);
        cloner.batchCloneFromTemplate(templateRef, targetFolderRef, targetResourcePoolRef, vmNames, 2, 4096);
    }
}

Key Things to Note

  • The Clone Method: The critical API call here is cloneVM_Task()—this is what tells vCenter to create a VM from an existing template, unlike the createVM_Task() method you found for fresh OS deployments.
  • Batch Handling: The example processes VMs sequentially, but if you need faster deployment, you can use a thread pool to run multiple clone tasks in parallel. Just be mindful of vCenter's concurrent task limits to avoid overwhelming it.
  • Customization: If you need unique settings (like different hostnames or IPs per VM), modify the createCustomizationSpec() method to generate a unique spec for each VM in the loop.
  • Error Handling: The example includes basic task waiting, but you should add error handling for cases where a clone fails (check taskInfo.getError()).

内容的提问来源于stack exchange,提问作者Shashi Ranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:33:02