Provisioning a VM from a template
Building a VM from a template is the classic Orchestrator job, and still one of the most common. The vSphere Client can do it in a wizard, but a workflow can do it the same way every time, from a script, a pipeline, or a request portal, and then carry on with the next steps: register the VM in DNS, add it to backup, tell the requester.
In this recipe you clone tpl-linux-01 twice. First with a library workflow, to see what’s involved. Then with Provision a VM from a template, a workflow of your own that applies the guest customization specification vcfguide-linux, sets the number of CPUs and the memory, waits for the clone to finish, and waits again until the new VM reports an IP address. Recipe 8.3 puts an approval in front of it.
Getting ready
- The actions
findVmByNameandwaitForTaskfrom recipe 8.1. - A Linux template in
vc01.vmw.lab, heretpl-linux-01, with VMware Tools (or open-vm-tools) installed. Guest customization needs them. - A guest customization specification in vCenter, here
vcfguide-linux, made in the vSphere Client under Policies and Profiles > VM Customization Specifications. Set the computer name to Use the virtual machine name, the time zone of your choice, and one NIC with DHCP. - A VM folder
vcfguide, and a cluster and datastore with room for two small VMs.
How to do it
Clone with a library workflow
- Go to Library > Workflows and open the folder Library > vCenter > Virtual Machine management > Clone. It holds Clone virtual machine, no customization, Clone virtual machine from properties, and Customize virtual machine from properties. The folders beside it hold clones with Linux or Windows customization and linked clones.
- Run Clone virtual machine, no customization. Pick
tpl-linux-01as the VM to clone, enter the namevcfguide-clone-01, choose the foldervcfguide, a host or resource pool in the cluster, and the datastore, and turn on power-on. - Click Run. The vSphere Client shows a Clone virtual machine task. When the run completes,
vcfguide-clone-01is in thevcfguidefolder, with the template’s name inside the guest, because nothing was customized. - Delete
vcfguide-clone-01in the vSphere Client, or with the library workflow Delete virtual machine.
On 9.1.1, Clone virtual machine, no customization is in Library > vCenter > Virtual Machine management > Clone, with Clone virtual machine from properties beside it. It asks for the VM or template, the VM folder, the name, whether to power on and whether to mark the copy as a template, and then for a datastore, a host and a resource pool, each optional, and thin provisioning. It returns newVM. Delete virtual machine is in the Basic folder of the same tree.
Offer only templates in the form
- Create the action
listTemplatesincom.vcfguide.chapter8, with no inputs and the return typeArray/VC:VirtualMachine:
var templates = [];var vms = VcPlugin.getAllVirtualMachines();for (var i = 0; i < vms.length; i++) { var config = vms[i].config; // config is null for VMs vCenter can't read, such as orphaned ones if (config && config.template) { templates.push(vms[i]); }}System.log(templates.length + " templates found");return templates;Build the clone
- Create the action
cloneFromTemplateincom.vcfguide.chapter8, with the return typeVC:Taskand these inputs:
| Input | Type |
|---|---|
template |
VC:VirtualMachine |
vmName |
string |
folder |
VC:VmFolder |
cluster |
VC:ClusterComputeResource |
datastore |
VC:Datastore |
specName |
string |
cpus |
number |
memoryMb |
number |
if (!template.config || !template.config.template) { throw template.name + " isn't a template";}
// Refuse a name that's already taken, in any registered vCenter.var taken = VcPlugin.getAllVirtualMachines(null, "xpath:name='" + vmName + "'");if (taken && taken.length > 0) { throw "A VM called " + vmName + " already exists";}
// Where the clone goesvar relocate = new VcVirtualMachineRelocateSpec();relocate.pool = cluster.resourcePool;relocate.datastore = datastore;
// What changes in the clone's hardwarevar config = new VcVirtualMachineConfigSpec();config.numCPUs = cpus;config.memoryMB = memoryMb;
var spec = new VcVirtualMachineCloneSpec();spec.location = relocate;spec.config = config;spec.template = false;spec.powerOn = true;
// The guest customization specification, read from the template's vCenterif (specName) { var manager = template.sdkConnection.customizationSpecManager; if (!manager.doesCustomizationSpecExist(specName)) { throw "No customization specification called " + specName + " in " + template.sdkConnection.id; } spec.customization = manager.getCustomizationSpec(specName).spec;}
System.log("Cloning " + template.name + " to " + vmName + " (" + cpus + " vCPU, " + memoryMb + " MB, spec " + (specName || "none") + ")");return template.cloneVM_Task(folder, vmName, spec);- Create the action
waitForGuestIpincom.vcfguide.chapter8, with the inputsvm(VC:VirtualMachine) andtimeoutSeconds(number), and the return typestring:
var deadline = new Date().getTime() + timeoutSeconds * 1000;var ip = null;
while (new Date().getTime() < deadline) { var guest = vm.guest; // Skip IPv6 link-local addresses that some guests report first if (guest && guest.ipAddress && guest.ipAddress.indexOf("fe80") !== 0) { ip = guest.ipAddress; break; } System.sleep(10000);}if (!ip) { throw vm.name + " reported no IP address within " + timeoutSeconds + " seconds";}System.log(vm.name + " has the IP address " + ip);return ip;Put it together
- Create the workflow Provision a VM from a template in VCF Orchestrator Guide/Chapter 8. On Inputs/Outputs, add the eight inputs of
cloneFromTemplatewith the same names and types, and two outputs:vm(VC:VirtualMachine) andipAddress(string). Add a variablecloneTask(VC:Task). - On the Schema tab, add three elements in a row:
- The action cloneFromTemplate, with all eight inputs bound to the workflow inputs and its result bound to
cloneTask. - A scriptable task
Wait for the clone, withcloneTaskin andvmout:
- The action cloneFromTemplate, with all eight inputs bound to the workflow inputs and its result bound to
// A clone with customization can take several minutesvm = System.getModule("com.vcfguide.chapter8").waitForTask(cloneTask, 1800);System.log("Clone finished: " + vm.name);- The action waitForGuestIp, with
vmin,timeoutSecondsset to the value900, and its result bound toipAddress.
- On the Input Form tab, give
templatethe value options External source with the actioncom.vcfguide.chapter8/listTemplates, so the field offers only templates, as in recipe 3.6. GivespecNamethe defaultvcfguide-linux,cpusthe default1, andmemoryMbthe default2048. GivevmNamea regular expression constraint of^[a-z][a-z0-9-]{1,14}$, which keeps the name valid as a Linux host name.
Schema tab of Provision a VM from a template: Start, cloneFromTemplate, Wait for the clone, waitForGuestIp, End. Beside it the Input Form tab with template selected, Values tab showing External source = com.vcfguide.chapter8/listTemplates.
- Run the workflow with
tpl-linux-01, the namevcfguide-web-01, the foldervcfguide, your cluster and datastore, and the defaults for the rest. - In the vSphere Client, watch the Clone virtual machine task, the VM powering on, and, in its Monitor > Events, the guest customization starting and finishing. The run waits in
Wait for the clone, then inwaitForGuestIp. - When the run completes, its Variables tab shows
vm=vcfguide-web-01and the IP address. Log in to the VM: its host name isvcfguide-web-01, set by the customization specification.
Completed run of Provision a VM from a template, Variables tab: vm = vcfguide-web-01, ipAddress = a lab address; Logs tab with Cloning tpl-linux-01 to vcfguide-web-01 (1 vCPU, 2048 MB, spec vcfguide-linux), Clone finished, has the IP address. Behind it, vSphere Client Monitor > Events of the new VM with Started customization and Customization succeeded.
Checked on 9.1.1 against the lab vCenter, with the script of step 7 and no customization specification:
VC:SdkConnectionhascustomizationSpecManager, and the manager hasdoesCustomizationSpecExistandgetCustomizationSpec.VcVirtualMachineRelocateSpec,VcVirtualMachineConfigSpecandVcVirtualMachineCloneSpectook every property used. The clone of a 1 vCPU template came up with 2 vCPU and 2048 MB, powered on, and VMware Tools started.task.info.resultofcloneVM_Taskis the newVC:VirtualMachine, sowaitForTaskreturns it.- Cloning a small Linux template on vSAN took several minutes. Allow for that in
timeoutSeconds. - For the first minutes,
vm.guest.ipAddressheld only an IPv6 link-local address (fe80:…), which is whywaitForIpskips those. On a network without DHCP, a clone without a customization specification never gets a usable address, andwaitForIptimes out as it should.
How it works
The clone spec. cloneVM_Task takes three things: the folder for the new VM, its name, and a VcVirtualMachineCloneSpec. The spec says everything else:
| Part of the spec | Set to | Says |
|---|---|---|
location |
a VcVirtualMachineRelocateSpec |
Where the clone runs and is stored: the resource pool (here the cluster’s root pool), the datastore, and optionally a host |
config |
a VcVirtualMachineConfigSpec |
Hardware changes made while cloning, here CPUs and memory |
customization |
the spec of a customization specification |
What to change inside the guest: host name, network, time zone |
template |
false |
Make a VM, not another template |
powerOn |
true |
Start it when the clone is done, which also starts the customization |
Guest customization. The customization specification is stored in vCenter, not in Orchestrator, so the people who look after templates can change it without touching the workflow. When the clone powers on, vCenter passes the settings into the guest through VMware Tools, and the guest applies them and usually reboots. That’s why the clone task finishing doesn’t mean the VM is ready, and why the workflow waits a second time, for the IP address.
The task result is the VM. The clone task’s info.result is the new VM, so waitForTask hands back a VC:VirtualMachine you can use straight away. There’s no need to search for the name you just created, and no risk of finding a different VM with the same name.
Fail early. cloneFromTemplate checks that the source is a template, that the name is free, and that the specification exists before it asks vCenter for anything. A request that would fail is stopped in a second with a clear message, instead of half way through a clone.
VcVirtualMachineCloneSpec in a scriptable task, and wait with vim3WaitTaskEnd.There's more
Clean up a failed build. If the clone succeeds and waitForGuestIp times out, the half-built VM is left behind. Add a Default error handler (recipe 3.4) with a scriptable task that checks whether vm is set and, if it is, powers it off with vm.powerOffVM_Task() and deletes it with vm.destroy_Task(), waiting for each with waitForTask. Log what it removed, so the requester knows why the VM is gone.
Templates in a content library. VCF 9 environments often keep VM templates in a content library rather than as templates in a VM folder. cloneVM_Task and listTemplates only see templates in the inventory. To deploy from a content library item, call the vSphere Automation REST API through the REST plug-in (recipe 5.2): the vcenter/vm-template/library-items deploy operation takes the item’s ID and a placement and returns the new VM’s ID.
On 9.1.1 the vSphere plug-in has no workflows or scripting classes for deploying from a content library: VC:ContentLibrary is an unknown type, and the API reference has only VcVirtualMachineContentLibraryItemInfo, which describes where a VM came from. Deploy from a content library through the vSphere Automation API instead, with the vAPI plug-in (recipe 8.10).
POST /api/vcenter/vm-template/library-items/{id}?action=deploy) from a REST host on 9.1.1 and record the request body.Linked clones. For many short-lived VMs, a linked clone shares the template’s disks and is created in seconds. The library has a Linked Clone folder with ready workflows. In your own spec, it’s two more lines: set spec.snapshot to a snapshot of the source VM, and relocate.diskMoveType to "createNewChildDiskBacking". The source must be a VM with a snapshot, not a template.
More than one NIC, or a fixed IP. The library workflows Clone, Linux with multiple NICs and Clone, Linux with a single NIC build the customization in the workflow instead of reading a stored specification. Read them for the VcCustomizationSpec objects to fill when each VM needs its own address. Many teams keep DHCP reservations or an IPAM system instead, and pass the address in.
Don’t start a hundred clones at once. Each clone is an I/O-heavy task on the datastore. vCenter queues tasks, but a workflow that starts many clones in parallel (recipe 3.8) can still make the storage slow for everyone. Limit the number of builds running at the same time with a lock (recipe 7.5) or a fixed number of parallel runs.
See also
- 8.1 Workflows against vCenter, for
findVmByName,waitForTask, and tasks. - 3.6 Input forms, for value options from an action.
- 3.4 Handling errors, for the default error handler.
- 8.3 An approval process for provisioning, which puts an approval in front of this workflow.
- VMware documentation (Aria Automation 8.12): Clone workflows, Linked clone workflows, and Linux customization clone workflows.
- Broadcom developer portal: CloneVMRequestType in the vSphere 9.0 Web Services API, and VM clone in the vSphere Automation API 9.1.
- Broadcom TechDocs (VCF 9.0): Configuring the vCenter Server plug-in.
