Skip to content

Scripts that read well

A script that works today gets read many more times than it gets written: by you next month, by a colleague at night, by whoever has to change it after a vCenter upgrade. These ten habits cost nothing extra while you write, and they make every later read faster. All the examples are plain ES5 and run as they are on Orchestrator 9.1.

Getting ready

  • Any action or scriptable task to practise on, such as the actions in com.vcfguide.chapter4 from recipe 4.2.
  • The rules in recipe 4.1: var, function, no arrow functions.

How to do it

1. Put the story at the top and the details below

Write the few lines that say what the script does first, then a divider, then one small function per step. Function declarations are hoisted, so the calls can come before the functions. Anyone can stop reading at the divider and still know what the script does.

com.vcfguide.chapter4/getUniqueDatastores — top-down
// Returns each datastore used by the given VMs, once.
var byId = indexDatastoresById(vms);
return valuesOf(byId);
///////////////// Details /////////////////
function indexDatastoresById(vms) {
var byId = new Properties();
for (var i = 0; i < vms.length; i++) {
var datastores = vms[i].datastore;
for (var j = 0; j < datastores.length; j++) {
byId.put(datastores[j].id, datastores[j]);
}
}
return byId;
}
function valuesOf(props) {
var values = [];
var keys = props.keys;
for (var i = 0; i < keys.length; i++) {
values.push(props.get(keys[i]));
}
return values;
}

In the lab, the three testvm VMs return one datastore: they all live on the same vSAN datastore.

2. Keep each function to 5–10 lines. If a function needs a comment to explain its parts, those parts want to be functions with good names.

3. Return early instead of else. Check the odd case first and leave; the normal case then reads without indentation.

function valueOrDefault(value, fallback) {
if (value !== null && value !== undefined && value !== "") {
return value;
}
return fallback;
}

4. Name your conditions. Move a long test into a function whose name says what it means: if (isFailedToken(token)) needs no comment.

function isFailedToken(token) {
return token.state === "failed" || token.state === "canceled";
}

5. Use a Properties object as a lookup table. Looping over one list inside another is slow on big inventories. Index one list by ID first, as indexDatastoresById does above, then look items up with get.

6. Get a module once, outside the loop. Each System.getModule(...) call looks the module up again. In a loop, keep it in a variable:

var vcTools = System.getModule("com.vcfguide.chapter4");
for (var i = 0; i < vms.length; i++) {
facts.push(vcTools.getVmFacts(vms[i]));
}

7. Build JSON with JSON.stringify, never with +. String concatenation breaks on the first quote or comma in a value.

var payload = JSON.stringify({ count: names.length, names: names });
// {"count":3,"names":["db01","web01","web02"]}

8. Return an empty array, not null. Callers loop over what you return; an empty array loops zero times, null throws.

9. Fail early, and say where. Validate inputs at the top and throw a message that names the action and the input, as recipe 4.2 does: throw "getVmFacts: the input vm is required";. When you catch an error from another system, add what you were trying to do before rethrowing it.

10. Let the vCenter do the filtering. VcPlugin.getAllVirtualMachines(null, "xpath:name[starts-with(.,'testvm')]") asks the vCenter for matching VMs only, instead of loading all of them and filtering in the script.

How it works

Orchestrator saves a run’s variables after every element: each element is a checkpoint. If the server restarts, the element that was running starts again from its first line. That is the reason for two more habits:

  • Pass simple values between elements: strings, numbers, Properties, inventory objects, or a JSON string. A JavaScript object with functions in it does not survive being saved.
  • Make each element safe to run twice. Ask what happens if it stops halfway and starts again: does it create a duplicate record, or a second snapshot? If the answer is yes, check before you create.

For the same reason, a loop built from elements, like the foreach element in recipe 3.3, resumes at the item it was on, while a loop inside one script starts again from the first item.

There's more

Comments say why, not what. The code shows what it does. Comment the odd thing: the API that needs a trailing slash, or the reason a value is hard-coded.

Logging. Log what someone will need at 3 a.m.: which object, which state, what you decided. Avoid Server.log for routine messages: it writes to the database and stays there. Recipe 4.6 has the details.

Ten to fifteen elements per workflow. When a schema grows beyond that, move a group of elements into a sub-workflow, and use workflow notes to label the regions that remain.

See also