Designing a solution from the bottom up
Most Orchestrator content that’s hard to maintain started as one workflow that grew. A few scriptable tasks became thirty, the inputs became a long form, and now nobody dares change it. This recipe does it the other way round, as VMware’s Coding Design Guide recommends: answer a few questions first, then build the smallest pieces, test each one on its own, and put them together last.
The example is one most teams need: decommissioning a VM. Someone asks for a VM to be retired. It’s powered off, marked with who asked and when, and moved to a holding folder. A few days later, if nobody has complained, a scheduled workflow deletes it. The rest of this chapter builds on it.
Getting ready
vc01.vmw.labregistered in Orchestrator (recipe 1.9), and a test VM you can power off and delete,vcfguide-test-01.- A VM folder for retired VMs in the lab data center,
vcfguide-retired. - The folders and names from recipe 9.3: the workflow folders under VCF Orchestrator Guide/Chapter 9, and the action modules
com.vcfguide.core.vcandcom.vcfguide.vm. - Recipes 4.2 (actions), 4.7 (configuration elements) and 8.1 (vCenter tasks), if you haven’t done them.
How to do it
A. Answer five questions before you build anything
Section titled “A. Answer five questions before you build anything”-
Write down the answers to the guide’s five questions for the solution. Keep them; they become the descriptions of your workflows.
Question Answer for decommissioning What is it for? Retire a VM safely: power it off, record who asked and why, park it for a few days, then delete it. Who runs it? People, from the client or a VCF Automation catalog item, with a ticket number. Later, a ticket tool through the REST API (recipe 9.2). The delete step runs on a schedule. What steps? Check the VM. Power it off, gently if possible. Write a note on the VM. Move it to the holding folder. Later: find parked VMs older than the grace period and delete them. What information? The VM, a ticket number, who asked, the holding folder, the grace period in days. Where does it come from? VM and ticket: inputs. Who asked: the user running the workflow. Folder and grace period: a configuration element, so they can change without touching code. -
Split the steps into automation and orchestration. Automation pieces each do one thing to one object: power off a VM, write a note, move a VM. Orchestration pieces put them in order and decide what happens when one fails. Figure 9.1 shows the result, one layer per row.
B. Build the bottom: one action per job
Section titled “B. Build the bottom: one action per job”-
Create the module
com.vcfguide.core.vcand copywaitForTaskinto it from recipe 8.1 (inputstask,VC:Task, andtimeoutSeconds,number; return typeAny). It’s shared content (recipe 9.3), so it knows nothing about decommissioning. -
In
com.vcfguide.vm, createpowerOffVm, with the inputsvm(VC:VirtualMachine) andtimeoutSec(number), and the return typestring. It asks the guest to shut down when VMware Tools is running, waits, and only then pulls the plug. It returns how the VM was stopped, so the caller can log it:
// Returns "already", "guest" or "hard". Throws if the VM can't be powered off.if (!vm) { throw "[VCFG][powerOffVm] vm is required";}var limitSec = timeoutSec > 0 ? timeoutSec : 300;
if (vm.runtime.powerState.value === "poweredOff") { System.log("[VCFG][powerOffVm] " + vm.name + " is already off"); return "already";}
if (vm.guest.toolsRunningStatus === "guestToolsRunning") { vm.shutdownGuest(); var deadline = new Date().getTime() + limitSec * 1000; while (new Date().getTime() < deadline) { System.sleep(5000); if (vm.runtime.powerState.value === "poweredOff") { System.log("[VCFG][powerOffVm] " + vm.name + " shut down from the guest"); return "guest"; } } System.warn("[VCFG][powerOffVm] " + vm.name + " didn't shut down in " + limitSec + " s, powering off");}
var task = vm.powerOffVM_Task();System.getModule("com.vcfguide.core.vc").waitForTask(task, 120);System.log("[VCFG][powerOffVm] " + vm.name + " powered off");return "hard";- Create
markVmRetired, with the inputsvm(VC:VirtualMachine),ticketId(string) andrequestedBy(string), and the return typestring. It adds one line to the VM’s notes and returns that line. The line starts with a fixed word and an ISO date, so the delete workflow can read it back:
// Adds "RETIRED <ISO date> ticket <id> by <user>" as the last line of the VM's notes.if (!vm || !ticketId) { throw "[VCFG][markVmRetired] vm and ticketId are required";}var line = "RETIRED " + new Date().toISOString() + " ticket " + ticketId + " by " + requestedBy;var notes = vm.config.annotation ? vm.config.annotation + "\n" : "";
var spec = new VcVirtualMachineConfigSpec();spec.annotation = notes + line;var task = vm.reconfigVM_Task(spec);System.getModule("com.vcfguide.core.vc").waitForTask(task, 120);
System.log("[VCFG][markVmRetired] " + vm.name + ": " + line);return line;- Create
moveVmToFolder, with the inputsvm(VC:VirtualMachine) andfolder(VC:VmFolder), and the return typevoid:
if (!vm || !folder) { throw "[VCFG][moveVmToFolder] vm and folder are required";}var task = folder.moveIntoFolder_Task([vm]);System.getModule("com.vcfguide.core.vc").waitForTask(task, 120);System.log("[VCFG][moveVmToFolder] " + vm.name + " moved to " + folder.name);And deleteVm, with the input vm (VC:VirtualMachine) and the return type string. It refuses a VM that’s still on, whoever calls it:
// Deletes a powered-off VM and returns its name. Throws if the VM is still on.if (!vm) { throw "[VCFG][deleteVm] vm is required";}if (vm.runtime.powerState.value !== "poweredOff") { throw "[VCFG][deleteVm] " + vm.name + " is not powered off, not deleted";}var name = vm.name;var task = vm.destroy_Task();System.getModule("com.vcfguide.core.vc").waitForTask(task, 300);System.log("[VCFG][deleteVm] deleted " + name);return name;- Test each action on its own before you go on, with Run on the action itself:
powerOffVmonvcfguide-test-01(run it twice; the second run returnsalready),markVmRetiredwith the ticketCHG-0001, andmoveVmToFolderintovcfguide-retired. Check each result in the vSphere Client. Then move the VM back and power it on for part C. LeavedeleteVmuntil part D.
Run of the action com.vcfguide.vm/markVmRetired on vcfguide-test-01 with ticketId = CHG-0001: the result RETIRED 2026-…Z ticket CHG-0001 by …, and the VM's Notes in the vSphere Client showing the same line.
C. The middle: one library workflow for the use case
Section titled “C. The middle: one library workflow for the use case”-
Create the configuration element
VCFG_Decommissionin the folder VCFG/VM (recipe 4.7), withretireFolder(VC:VmFolder) set tovcfguide-retired, andgraceDays(number) set to7. Set the values by hand for now; recipe 9.4 sets them with a workflow, so that the element can travel in a package without them. -
In VCF Orchestrator Guide/Chapter 9/04 Library/VM, create the workflow VCFG - LIB - Retire VM, with the inputs
vm(VC:VirtualMachine),ticketId(string),requestedBy(string) andretireFolder(VC:VmFolder), and the outputretiredNote(string). Its schema is a scriptable task,Check inputs, then three Action elements in a row,powerOffVm,markVmRetiredandmoveVmToFolder, bound to those inputs, with the variabletimeoutSec=300. It has no form: it’s called by other workflows, not by people. The first task checks every input before anything touches the VM:
// Check everything first, so a bad input fails before the VM is touched.var missing = [];if (!vm) { missing.push("vm"); }if (!ticketId) { missing.push("ticketId"); }if (!requestedBy) { missing.push("requestedBy"); }if (!retireFolder) { missing.push("retireFolder"); }if (missing.length > 0) { throw "[VCFG][Retire VM] missing input: " + missing.join(", ");}- Fill in its Description with the contract, the promise it makes to every caller:
Powers off a VM (guest shutdown first, hard power-off after 5 minutes),adds "RETIRED <ISO date> ticket <ticketId> by <requestedBy>" to its notes,and moves it to retireFolder. Returns that note line.Checks all inputs before it changes anything. Fails, and changes nothing more,if any step fails: a VM that won't power off is not marked or moved.Safe to run again on a VM that is already off.-
Run it on
vcfguide-test-01with a ticket number, your user and the retired folder. The VM ends up off, noted and moved, andretiredNoteholds the line. -
Next to it, create the second library workflow, VCFG - LIB - Delete VM, with the input
vm(VC:VirtualMachine) and the outputdeletedName(string). Its schema is one Action element,deleteVm. Its description is its contract:
Deletes a VM that is powered off and returns its name.Refuses, and changes nothing, if the VM is powered on.Callers decide which VMs to delete; this workflow doesn't check notes or dates.Deleting isn’t part of retiring, so it gets its own library workflow rather than a switch on Retire VM. Each library workflow keeps one promise.
D. The top: thin entry workflows
Section titled “D. The top: thin entry workflows”- In VCF Orchestrator Guide/Chapter 9/01 Catalog/VM, create VCFG - VM - Decommission VM, with the inputs
vmandticketId, and the variableretireFolder, bound toVCFG_Decommission(Bind to configuration, as in recipe 4.7). Add a scriptable task,Who asked, that sets the variablerequestedBy:
requestedBy = Server.getRunningUser(); // a string on 9.1.1, not a user objectif (!/^[A-Z]+-\d+$/.test(ticketId)) { throw "[VCFG][Decommission VM] ticketId must look like CHG-1234, got: " + ticketId;}Then a Workflow element that calls VCFG - LIB - Retire VM. Give the form a VM picker and a ticket field, and nothing else: the folder comes from configuration, the requester from the login.
- In 05 Utilities, create VCFG - VM - Delete Retired VMs, with no inputs, the output
deletedCount(number), and the variablesretireFolderandgraceDays, both bound toVCFG_Decommission. One scriptable task reads the lastRETIREDline of each VM in the folder and, for each VM older than the grace period, runs VCFG - LIB - Delete VM. Copy the ID of VCFG - LIB - Delete VM from its General tab into the first line:
// Finds VMs in retireFolder retired more than graceDays ago and deletes each one// through the library workflow VCFG - LIB - Delete VM.var DELETE_VM_ID = "<id of VCFG - LIB - Delete VM>"; // VCFG - LIB - Delete VMvar deleteVmWorkflow = Server.getWorkflowWithId(DELETE_VM_ID);if (!deleteVmWorkflow) { throw "[VCFG][Delete Retired VMs] library workflow not found: " + DELETE_VM_ID;}if (!retireFolder || !(graceDays >= 0)) { throw "[VCFG][Delete Retired VMs] retireFolder and graceDays must be set in VCFG_Decommission";}var cutoff = new Date().getTime() - graceDays * 24 * 3600 * 1000;
var vms = []; // the VMs directly in the foldervar children = retireFolder.childEntity;for (var c = 0; c < children.length; c++) { if (children[c] instanceof VcVirtualMachine) { vms.push(children[c]); }}
deletedCount = 0;for (var i = 0; i < vms.length; i++) { var notes = vms[i].config.annotation || ""; var match = notes.match(/RETIRED (\S+) ticket (\S+)/g); if (!match) { System.warn("[VCFG][Delete Retired VMs] " + vms[i].name + " has no RETIRED note, skipped"); continue; } var last = match[match.length - 1].split(" "); var retiredOn = new Date(last[1]).getTime(); if (isNaN(retiredOn) || retiredOn > cutoff) { System.log("[VCFG][Delete Retired VMs] " + vms[i].name + " retired " + last[1] + ", kept"); continue; } if (vms[i].runtime.powerState.value !== "poweredOff") { System.warn("[VCFG][Delete Retired VMs] " + vms[i].name + " was powered on again, skipped"); continue; }
var params = new Properties(); params.put("vm", vms[i]); var token = deleteVmWorkflow.execute(params); var deadline = new Date().getTime() + 10 * 60000; while (token.state === "running" || token.state === "waiting") { if (new Date().getTime() > deadline) { throw "[VCFG][Delete Retired VMs] delete of " + vms[i].name + " still running after 10 min"; } System.sleep(2000); } if (token.state !== "completed") { System.error("[VCFG][Delete Retired VMs] " + vms[i].name + " not deleted: " + token.exception); continue; } System.log("[VCFG][Delete Retired VMs] deleted " + vms[i].name + " (ticket " + last[3] + ")"); deletedCount++;}System.log("[VCFG][Delete Retired VMs] " + deletedCount + " VM(s) deleted");The script finds the library workflow by ID, not by name, so it still works after a package import moves it to another folder. It waits for each delete with a deadline, and a VM that fails to delete is logged and skipped rather than stopping the rest. The folder’s vm property would be shorter than childEntity, but the vSphere API marks it as deprecated.
Schedule it once a day (recipe 7.7). A VM someone powered on again is never deleted: that’s how a person says “wait”.
Library > Workflows, tree view of VCF Orchestrator Guide/Chapter 9 with VCFG - VM - Decommission VM in 01 Catalog/VM, VCFG - LIB - Retire VM in 04 Library/VM, VCFG - VM - Delete Retired VMs in 05 Utilities; and VCFG - LIB - Delete VM in 04 Library/VM; beside it, the schema of VCFG - LIB - Retire VM with Check inputs and its three action elements.
VcVmFolder.vm is deprecated, so the delete script lists a folder’s VMs from childEntity with instanceof VcVirtualMachine. Server.getRunningUser() returns a string. An empty vm.config.annotation is “”. A VC:VmFolder in a configuration element can be bound to a workflow variable. A VM powered on seconds before the run gets a hard power-off, because VMware Tools isn’t running yet. Without Check inputs, an unbound folder let the VM be powered off and noted before the move failed.How it works
Bottom-up makes the parts testable. Every action in part B runs on its own with a few typed inputs, so you test it before anything depends on it. When the library workflow fails, you already know which pieces work. VMware’s guide goes further: the first workflow you build to try an integration becomes the test of the action that replaces it, and nobody calls it in production again (recipe 9.6).
Automation below, orchestration above. The actions know how to do one thing to one VM. The library workflow knows the order, and that a VM that won’t power off must not be marked or moved. The entry workflows know only how their caller talks: a form and a login, or a schedule. Each layer can change without the others: a ticket tool becomes a second entry workflow, not a change to the library workflow.
Sever the caller early. The entry workflow turns “the person logged in” into the string requestedBy, and the configuration into a folder. Below it, nothing reads a login, a form, or a VCF Automation property. That’s what lets the same library workflow serve the client, a catalog item, the REST API and a test (recipe 9.2).
Design by contract. The description in step 10 is a promise: what the workflow does, what it returns, and what happens when it fails. Callers can rely on it without reading the schema, and anyone who changes the workflow knows what they mustn’t break. The guide’s advice is to validate before you return, so that callers don’t each have to check for null and empty values.
Smaller is easier to read. The guide suggests keeping a workflow to 10 to 15 elements. If a schema needs more, part of it is probably a library workflow or an action waiting to be pulled out. Readers who understand the top layer understand what the solution does, even before they read any code.
There's more
Rollback. If moving the VM fails after it was powered off and marked, the library workflow stops with the VM off and noted but not moved. That’s safe, and running it again finishes the job, because powerOffVm returns already. For steps that aren’t safe to repeat, add a Default error handler that undoes what was done (recipe 3.4).
Approval first. For production, put an approval in front of the library workflow in the entry workflow (recipe 8.3), not inside it, so that the scheduled and API callers can decide for themselves.
Day-2 action in VCF Automation. The same library workflow can back a VCF Automation day-2 action on deployed VMs. Recipe 9.2 shows the directions; recipe 8.8 shows a resource action.
See also
- 9.2 Choosing the integration direction.
- 9.3 Folders, modules, and names, for the names used here.
- 8.1 Workflows against vCenter, for
waitForTaskand vCenter tasks. - 3.4 Handling errors and exceptions.
- VMware: vRealize Orchestrator Coding Design Guide, technical white paper, March 2016 (sections Solution Design, Bottom Up Approach, Workflow Separation and Individual Workflows).
