Skip to content

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.lab registered 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

  1. 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.
  2. Open Create a snapshot and click Run. Pick vcfguide-test-01 in the VM picker, which browses the live inventory of vc01.vmw.lab. Enter the name before-ch8, leave memory and quiesce off, and click Run.
  3. 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).
Figure 8.1. The vSphere plug-in's snapshot workflows in the library.

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.

Needs a lab check. Record the input labels of Create a snapshot on 9.1.1.

List the vCenter connections from a script

  1. In the API Explorer, search for VcPlugin. It’s the plug-in’s entry point. allSdkConnections returns one VC:SdkConnection for each registered vCenter, and the getAll… methods return every object of one type across all of them.
  2. Create the action describeVcenters in com.vcfguide.chapter8, with no inputs and the return type Array/string:
com.vcfguide.chapter8/describeVcenters
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;
  1. Run it. The log has one line for vc01.vmw.lab, with its version and build.
Figure 8.2. Reading the vCenter connections from a script.

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

  1. Chapter 3’s findVmsByName reads 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 action findVmByName in com.vcfguide.chapter8, with the input vmName (string) and the return type VC:VirtualMachine:
com.vcfguide.chapter8/findVmByName
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];
  1. 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.

Needs a lab check. Compare the run time of findVmByName with findVmsByName on a large inventory.

Start a task and wait for it

  1. Create the action waitForTask in com.vcfguide.chapter8, with the inputs task (VC:Task) and timeoutSeconds (number), and the return type Any. It returns the task’s result, or throws if the task fails or takes too long:
com.vcfguide.chapter8/waitForTask
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;
  1. Create the action snapshotVm in com.vcfguide.chapter8, with the inputs vm (VC:VirtualMachine) and snapshotName (string), and the return type VC:VirtualMachineSnapshot:
com.vcfguide.chapter8/snapshotVm
var description = "Taken by Snapshot a VM on " + new Date().toString();
// name, description, include memory, quiesce the guest file system
var 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;
  1. Create the workflow Snapshot a VM in VCF Orchestrator Guide/Chapter 8. Drag snapshotVm onto its schema and click Promote: make vm and snapshotName inputs and the result an output called snapshot.
  2. Run it on vcfguide-test-01 with the name ch8-script. When the run completes, the VM’s snapshot manager in the vSphere Client shows before-ch8 and ch8-script.
  3. Remove both: run the library workflow Remove all snapshots on vcfguide-test-01, or delete them in the vSphere Client.
Figure 8.3. A workflow that starts a vCenter task and waits for it.

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.

Back in vRO 5.5–7Script against the vCenter plug-in with VcPlugin and VC: types, and wait for tasks with vim3WaitTaskEnd.
In Orchestrator 9.xThe same objects and methods, in a browser editor with the API Explorer beside it. Code from vRO 7 for VM operations usually runs unchanged; check deprecated vSphere API methods against the vSphere 9 API reference.

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.

Needs a lab check. After upgrading the lab to 9.1.1, restart 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:

com.vcfguide.chapter8/findVmsByNameWithPc
// 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