Workflows against vCenter
Recipe 1.9 registered vc01.vmw.lab, and many recipes since then have read VMs from it. This recipe looks at the vSphere plug-in more closely, because every other recipe in the chapter depends on it. You run one of the workflows it ships with, see how its scripting objects map to the vSphere API, find a single VM by name without reading the whole inventory, and start a vCenter task and wait for it to finish.
The task in this recipe is a snapshot of one test VM. It’s quick, it’s easy to undo, and it shows the pattern used by every vCenter change: call a method that ends in _Task, wait for the task, and read its result.
Getting ready
vc01.vmw.labregistered in Orchestrator, as in recipe 1.9.- A test VM you can snapshot, here
vcfguide-test-01. Any small powered-on VM with VMware Tools will do. - The folder VCF Orchestrator Guide/Chapter 8 and the action module
com.vcfguide.chapter8. - The API Explorer from recipe 4.2.
How to do it
Run a library workflow
- Go to Library > Workflows and search for
snapshot. The vSphere plug-in’s snapshot workflows are in the folder Library > vCenter > Virtual Machine management > Snapshot. - Open Create a snapshot and click Run. Pick
vcfguide-test-01in the VM picker, which browses the live inventory ofvc01.vmw.lab. Enter the namebefore-ch8, leave memory and quiesce off, and click Run. - In the vSphere Client, open the VM’s Monitor > Tasks. A Create virtual machine snapshot task appears, started by the account that Orchestrator uses for
vc01(recipe 1.9).
Library > Workflows, tree open at Library > vCenter > Virtual Machine management > Snapshot, the snapshot workflows listed; Create a snapshot run form open beside it with vcfguide-test-01 picked and name before-ch8.
On 9.1.1 the folder holds Create a snapshot, Create snapshots of all virtual machines in a resource pool, Remove all snapshots, Remove excess snapshots, Remove old snapshots, Remove snapshots of a given size, Revert to current snapshot and Revert to snapshot and wait.
List the vCenter connections from a script
- In the API Explorer, search for
VcPlugin. It’s the plug-in’s entry point.allSdkConnectionsreturns oneVC:SdkConnectionfor each registered vCenter, and thegetAll…methods return every object of one type across all of them. - Create the action
describeVcentersincom.vcfguide.chapter8, with no inputs and the return typeArray/string:
var lines = [];var connections = VcPlugin.allSdkConnections;for (var i = 0; i < connections.length; i++) { var sdk = connections[i]; var about = sdk.about; // id is the host name; name is the full SDK URL, https://…:443/sdk var line = sdk.id + ": " + about.fullName + " (API " + about.apiVersion + ")"; lines.push(line); System.log(line);}if (lines.length === 0) { System.warn("No vCenter is registered with the vSphere plug-in");}return lines;- Run it. The log has one line for
vc01.vmw.lab, with its version and build.
Run of action describeVcenters, Logs tab: one line vc01.vmw.lab: VMware vCenter Server 9.x … (API 9.x); result array with the same line.
In the 9.1.1 lab the line reads vc01.example.com: VMware vCenter Server 9.1.1.0.25712839 (API 9.1.1.0). Use the connection’s id for the host name: its name is the whole SDK address, such as https://vc01.example.com:443/sdk.
Find one VM by name
- Chapter 3’s
findVmsByNamereads every VM and tests each name. That’s fine in a lab, and slow with thousands of VMs. When you know the exact name, let the plug-in filter for you. Create the actionfindVmByNameincom.vcfguide.chapter8, with the inputvmName(string) and the return typeVC:VirtualMachine:
if (!vmName) { throw "findVmByName: vmName is empty";}if (vmName.indexOf("'") >= 0) { throw "findVmByName: names with an apostrophe aren't supported: " + vmName;}
// The plug-in filters by name before it builds the VM objects.var query = "xpath:name='" + vmName + "'";var vms = VcPlugin.getAllVirtualMachines(null, query);
if (!vms || vms.length === 0) { throw "No VM called " + vmName + " in any registered vCenter";}if (vms.length > 1) { var where = []; for (var i = 0; i < vms.length; i++) { where.push(vms[i].sdkConnection.id); } throw vms.length + " VMs are called " + vmName + ", in " + where.join(", ");}System.log("Found " + vmName + " in " + vms[0].sdkConnection.id + " (" + vms[0].id + ")");return vms[0];- Run it with
vcfguide-test-01, then with a name that doesn’t exist. The first run returns the VM. The second fails with No VM called ….
Checked on 9.1.1: getAllVirtualMachines(null, "xpath:name='testvm01'") returned exactly one VM, with id = vm-61 (the vCenter managed object ID) and sdkConnection.id = the vCenter’s host name.
findVmByName with findVmsByName on a large inventory.Start a task and wait for it
- Create the action
waitForTaskincom.vcfguide.chapter8, with the inputstask(VC:Task) andtimeoutSeconds(number), and the return typeAny. It returns the task’s result, or throws if the task fails or takes too long:
var deadline = new Date().getTime() + timeoutSeconds * 1000;var state = task.info.state.value;
while (state === "queued" || state === "running") { if (new Date().getTime() > deadline) { throw "Task " + task.info.descriptionId + " still " + state + " after " + timeoutSeconds + " seconds"; } System.sleep(2000); state = task.info.state.value;}
if (state === "error") { throw "Task " + task.info.descriptionId + " failed: " + task.info.error.localizedMessage;}System.log("Task " + task.info.descriptionId + " finished");return task.info.result;- Create the action
snapshotVmincom.vcfguide.chapter8, with the inputsvm(VC:VirtualMachine) andsnapshotName(string), and the return typeVC:VirtualMachineSnapshot:
var description = "Taken by Snapshot a VM on " + new Date().toString();// name, description, include memory, quiesce the guest file systemvar task = vm.createSnapshot_Task(snapshotName, description, false, false);System.log("Started snapshot " + snapshotName + " of " + vm.name);
var snapshot = System.getModule("com.vcfguide.chapter8").waitForTask(task, 300);System.log("Snapshot " + snapshotName + " of " + vm.name + " is ready");return snapshot;- Create the workflow Snapshot a VM in VCF Orchestrator Guide/Chapter 8. Drag snapshotVm onto its schema and click Promote: make
vmandsnapshotNameinputs and the result an output calledsnapshot. - Run it on
vcfguide-test-01with the namech8-script. When the run completes, the VM’s snapshot manager in the vSphere Client showsbefore-ch8andch8-script. - Remove both: run the library workflow Remove all snapshots on
vcfguide-test-01, or delete them in the vSphere Client.
Completed run of Snapshot a VM: Variables tab with input vm = vcfguide-test-01 and output snapshot (a VC:VirtualMachineSnapshot); Logs tab with Started snapshot ch8-script …, Task … finished, Snapshot ch8-script of vcfguide-test-01 is ready.
Checked on 9.1.1 with a snapshot of a lab VM: polling task.info.state.value every 300 ms saw running and then success, so task.info is read again on each access. task.info.descriptionId was VirtualMachine.createSnapshot, task.info.result was a VC:VirtualMachineSnapshot, and its removeSnapshot_Task(false, true) removed it again. The library workflow is called Remove all snapshots.
How it works
The plug-in is the vSphere API. The vSphere plug-in doesn’t invent its own model of vCenter. It wraps the vSphere Web Services API, the same API that PowerCLI and the vSphere SDKs use, and gives each managed object and data object a scripting type with a VC: or Vc prefix. A VirtualMachine in the API is a VC:VirtualMachine in Orchestrator, a VirtualMachineCloneSpec is a VcVirtualMachineCloneSpec, and the method CreateSnapshot_Task is createSnapshot_Task on the VM object. When you need something the library workflows don’t do, look it up in the vSphere API reference, then find the same name in the API Explorer.
_Task methods return at once. A method whose name ends in _Task asks vCenter to start the work and returns a VC:Task straight away, usually before anything has changed. The work is done when the task’s info.state is success, and the new object, if there is one, is in info.result. That’s why every change in this chapter is followed by a wait. Skip the wait and the next step works on a VM that isn’t there yet.
Three ways to wait. waitForTask polls every two seconds, as the library action vim3WaitTaskEnd in com.vmware.library.vc.basic does. Unlike that action, it has a deadline, so a stuck task can’t hold a run for ever. A polling loop keeps the run’s thread busy, which is fine for tasks of a few minutes. For tasks that can take an hour, use the Waiting event element with task.createEndOfTaskTrigger(timeoutSeconds), as in recipe 3.7, and the run sleeps in the database instead.
Finding objects. VcPlugin.getAllVirtualMachines() without arguments builds an object for every VM in every vCenter. The second argument is a query, and with xpath: the plug-in filters on its side before it builds the objects. Broadcom’s 8.x documentation recommends always passing a query to the getAll… and findAll… finders for this reason. Server.findAllForType("VC:VirtualMachine", query) asks the same plug-in, so it behaves the same way.
One shared account, or the person who ran it. The task in step 3 was started by the account in the vCenter connection, unless you chose a session per user in recipe 1.9. That decides what vCenter’s task list and events show, and whose permissions apply.
VcPlugin and VC: types, and wait for tasks with vim3WaitTaskEnd.There's more
When the vCenter connection breaks. Broadcom has three 9.x knowledge base articles on the vSphere plug-in losing its session with vCenter, usually after vCenter restarts or closes old sessions. The vCenter shows as unusable in the inventory, and vco-app.log has SDK in bad health. KB 452127 covers 9.1.0 and says the fix is targeted for 9.1.1. KB 435506 offers a patched plug-in for 9.0.x. The workaround in each is the library workflow Update a vCenter Server instance, which re-authenticates the connection.
vc01.vmw.lab and check whether the vCenter connection in Orchestrator recovers by itself (the KB 452127 fix), or still needs Update a vCenter Server instance.Never pass on an empty result. KB 432269 describes a provisioning workflow that searched the whole inventory for a VM while one vCenter was unusable. The search returned nothing, the next step got undefined, and it failed with a confusing error far from the cause. findVmByName throws when it finds nothing, so the error says what went wrong. Do the same in every action that looks something up.
If a search misses VMs that exist. KB 438935 describes Server.findAllForType("VC:VirtualMachine", "xpath:name='…'") sometimes returning nothing for a VM that’s in vCenter, after changes to the plug-in’s caching in the 8.18 timeframe. Its advice is to ask vCenter directly with the vSphere PropertyCollector. On 9.1.1 the library has that approach in the folder Property collector: Get virtual machines by name with PC calls Get vCenter entities by properties, which builds a container view and a property filter. This action does the same in one script, for one vCenter:
// Inputs: vc (VC:SdkConnection), namePattern (string). Returns Array/VC:VirtualMachine.// Asks vCenter for the name of every VM, so it never depends on the plug-in's cache.var pattern = new RegExp(namePattern);var view = vc.viewManager.createContainerView(vc.rootFolder, ["VirtualMachine"], true);var collector = vc.propertyCollector.createPropertyCollector();var result = [];try { var traversal = new VcTraversalSpec(); traversal.name = "traverseView"; traversal.type = "ContainerView"; traversal.path = "view"; traversal.skip = false;
var objectSpec = new VcObjectSpec(); objectSpec.obj = view.reference; objectSpec.skip = true; objectSpec.selectSet = [traversal];
var propertySpec = new VcPropertySpec(); propertySpec.type = "VirtualMachine"; propertySpec.pathSet = ["name"];
var filterSpec = new VcPropertyFilterSpec(); filterSpec.objectSet = [objectSpec]; filterSpec.propSet = [propertySpec];
var page = collector.retrievePropertiesEx([filterSpec], new VcRetrieveOptions()); while (page) { var objects = page.objects || []; for (var i = 0; i < objects.length; i++) { if (pattern.test(objects[i].propSet[0].val)) { result.push(VcPlugin.convertToVimManagedObject(vc, objects[i].obj)); } } page = page.token ? collector.continueRetrievePropertiesEx(page.token) : null; }} finally { collector.destroyPropertyCollector(); view.destroyView();}System.log(result.length + " VMs in " + vc.id + " match /" + namePattern + "/");return result;Run in the 9.1.1 lab with ^rocky, it returned the two VC:VirtualMachine objects whose names start with rocky. The finally block removes the view and the collector, which otherwise stay on vCenter until the session ends. On the lab’s 105 VMs it took 93 ms, against 32 ms for a loop over the plug-in’s cached getAllVirtualMachines(), so use it where the cache lets you down or the inventory is large, not by default.
Read properties once. Each property you read on a vCenter object can mean a call to vCenter. In a loop over many VMs, read what you need into local variables once, as waitForTask does with state, and don’t read vm.config or vm.summary again and again. Broadcom’s 8.x documentation adds that each reference to a vCenter object held in a workflow attribute or parameter sends a query to vCenter, and suggests keeping such objects in a configuration or resource element when a workflow refers to them often.
Clean up after yourself. A snapshot taken by automation and forgotten slows the VM and fills the datastore. A workflow that takes a snapshot before a change should remove it when the change succeeds, with snapshot.removeSnapshot_Task(false, true) and a wait, and leave it, with a log line saying so, when the change fails.
See also
- 1.9 Registering your first vCenter, for the connection and the session-per-user choice.
- 3.7 Waiting and custom events, for waiting on a vCenter task with a trigger.
- 5.1 How plug-ins work, for the inventory and
Server.findAllForType. - 8.2 Provisioning a VM from a template, which uses
findVmByNameandwaitForTask. - Broadcom TechDocs (VCF 9.0): Configuring the vCenter Server plug-in and Plug-ins installed with the VCF Operations orchestrator server.
- VMware documentation (Aria Automation 8.12): vCenter plug-in workflow library and Using XPath expressions with the vCenter plug-in.
- Broadcom KB 452127, 435506, 432269 and 438935.
- CloudBlogger, the author’s blog: Get VM (VC:VirtualMachine) using MoRefId, Managing vSphere VM Advanced Configuration Parameters with Orchestrator, Decode SCSI Controllers with Orchestrator Code, Enabling vTPM in vSphere VMs using Orchestrator.
