Guest OS Script Engine: one Orchestrator workflow for scripts inside any VM

Guest OS Script Engine is my Orchestrator workflow for running Bash, PowerShell and Batch scripts inside Linux and Windows VMs through VMware Tools. Here’s how it works, how to call it, and what I tested.

Banner: Guest OS Script Engine sends a script through VMware Tools to Linux (bash) and Windows (PowerShell, Batch) VMs and returns output and exit code
In this article

Guest OS Script Engine is an Orchestrator workflow that runs a script inside a VM through VMware Tools: Bash on Linux, PowerShell or Batch on Windows. It was previously called Run Script in Linux or Windows (Consolidated).

For version 1.2.0 I fixed the bugs I found, added two optional inputs and tested it on Linux and Windows VMs. This post covers what it does, how to call it from your own workflow, what I tested and the gotchas I hit.

Tested on: VCF Operations Orchestrator 9.1.1 (build 25643527) embedded in VCF Automation 9.1.1, against an Ubuntu VM (Bash) and a Windows Server 2022 VM (PowerShell and Batch) on vSphere 9. Guest OS Script Engine version 1.2.0.

What it does

You give it a VM, guest credentials, a script stored in a Resource Element and the script type. It copies the script into the guest, runs it, waits for it to finish and hands you back the output and the exit code. Everything goes through the vSphere guest operations API, so the VM doesn’t need SSH, WinRM or even a network connection to Orchestrator.

  • Linux: bash, sh or shell
  • Windows: powershell, batch or bat
  • Placeholders: write [KEY] anywhere in the script and pass KEY in scriptVariables; [hostname] defaults to the VM name
  • One script per VM at a time: a second run on the same VM waits for the first one
  • Clean guest: the temporary script and output files are removed, also when something fails

How it works

The whole thing is one scriptable task. These are the steps it goes through:

  1. Validate the inputs: vm and resourceElement are required
  2. Concurrency guard: if another run is active on the same VM, wait 30 seconds and check again, up to 12 times (6 minutes)
  3. Readiness check: the VM must be powered on and VMware Tools ready for guest operations; it retries toolsErrorRetryMax times with a random 10-70 second wait
  4. Detect the guest OS family (Windows or Linux)
  5. Read the raw script body from the Resource Element
  6. Check that scriptType is supported and matches the guest OS, before anything is copied to the guest. Resolve the timeout and working directory, and strip Windows line endings for Linux
  7. Replace every [KEY] with its value from scriptVariables, and warn about placeholders left over
  8. Log in to the guest with vmUsername and vmPassword
  9. Create a temporary output file, wrap the script so all output goes into it, and upload the script
  10. Linux only: make the script executable (0755)
  11. Start it with bash, powershell.exe or cmd.exe, and check every 5 seconds until it ends. On timeout the guest process is terminated and the workflow fails
  12. Windows only: clean up the output encoding with the cmdANSI utility
  13. Download the output file and return scriptOutputTextOut and scriptExitCodeOut
  14. Clean up, on success and on failure: delete the files in the guest and the temporary files on Orchestrator
Guest OS Script Engine workflow summary in Orchestrator, showing version 1.2.0, its folder and the description with the flow
The workflow in Automation Library/Guest Operations, version 1.2.0

Inputs and outputs

InputTypeRequiredWhat it’s for
vmVC:VirtualMachineYesThe VM to run the script in. Powered on, with VMware Tools running
scriptTypestringYesbash, sh, shell, powershell, batch or bat. Checked against the guest OS
vmUsernamestringYesGuest OS account
vmPasswordSecureStringYesGuest OS password. Keep it in a configuration element, not in code
resourceElementResourceElementYesThe script body, nothing else
scriptVariablesPropertiesNoValues for the [KEY] placeholders, inserted exactly as given
toolsErrorRetryMaxstringNoHow often to re-check VMware Tools readiness (default 5)
debugbooleanNoExtra logging. Variable values are never logged
scriptTimeoutSecnumberNoMaximum run time in seconds. Empty or 0 means 360
scriptWorkingDirectorystringNoGuest folder for the temporary files. Empty means C:\Windows\Temp or /tmp

Two outputs come back: scriptOutputTextOut (stdout and stderr together) and scriptExitCodeOut.

Inputs and outputs of the Guest OS Script Engine workflow in the Orchestrator workflow editor
Inputs and outputs in the workflow editor

Calling it from your own workflow

Here’s a complete example. First, a small Bash script saved as a Resource Element (mine is lab-gse-demo.sh). [GREETING] is a placeholder:

echo "[GREETING] on $(hostname)"
uptime -p
df -h / | tail -1

Then, in any scriptable task, call the engine by its ID and wait for it with a deadline. The variables vm, guestUsername, guestPassword and scriptElement are your own inputs or attributes:

var GUEST_ENGINE_ID = "83a44b2f-24fa-40cc-b786-a805ba7e3f89"; // Guest OS Script Engine
var engine = Server.getWorkflowWithId(GUEST_ENGINE_ID);
if (!engine) {
throw "Guest OS Script Engine not found: " + GUEST_ENGINE_ID;
}
var vars = new Properties();
vars.put("GREETING", "Hello from Orchestrator");
var params = new Properties();
params.put("vm", vm);
params.put("scriptType", "bash");
params.put("vmUsername", guestUsername);
params.put("vmPassword", guestPassword);
params.put("resourceElement", scriptElement);
params.put("scriptVariables", vars);
params.put("toolsErrorRetryMax", "5");
params.put("debug", false);
params.put("scriptTimeoutSec", 120);
var token = engine.execute(params);
var deadline = new Date().getTime() + 10 * 60000;
while (token.state === "running" || token.state === "waiting" || token.state === "waiting-signal") {
if (new Date().getTime() > deadline) {
throw "Guest script did not finish in 10 minutes (token " + token.id + ")";
}
System.sleep(5000);
}
if (token.state !== "completed") {
throw "Guest script failed: " + token.exception;
}
var outputs = token.getOutputParameters();
var exitCode = String(outputs.get("scriptExitCodeOut"));
var output = String(outputs.get("scriptOutputTextOut") || "").replace(/^\uFEFF/, "");
if (exitCode !== "0") {
throw "Guest script exited with " + exitCode + ": " + output;
}
System.log(output);

Output:

Hello from Orchestrator on lab-linux01
up 2 weeks, 10 hours, 24 minutes
/dev/sda1 29G 2.8G 26G 10% /

A non-zero exit code does not fail the workflow. Guest OS Script Engine only fails when it can’t run the script (no VMware Tools, wrong password, timeout and so on). If your script exits with 1, the run is still green, so always check scriptExitCodeOut like the example does, or have the script print a marker such as RESULT=0 and look for it.

Look it up with Server.getWorkflowWithId(), not by name. The ID stays the same when you import the package into another Orchestrator.

Run log of a successful Guest OS Script Engine run of the demo Bash script on a Linux VM, ending with exit code 0
Run log of the example above

What I tested

I ran these in my lab against an Ubuntu VM and a Windows Server 2022 VM, using harmless commands only (echo, hostname, sleep, exit). The first set ran on 1.1.0 and the input-related ones on 1.2.0; the logic for the first set didn’t change in 1.2.0.

ScenarioGuestResult
Happy pathLinux (bash), Windows (PowerShell, Batch)Output and exit code 0 returned
Value containing $$ and $&Linux, WindowsInserted exactly as given
Placeholder without a valueLinuxWarning in the log, script still runs
exit 3, exit 2, exit /b -1Linux, WindowsRun completes, the real exit code is returned (including -1)
Windows line endings in a Bash scriptLinuxStripped, script runs
stdout plus stderr, PowerShell warning and error streamsLinux, WindowsAll captured
PowerShell on Linux, Bash on Windows, pythonBothFails in about 2 seconds, before anything is copied to the guest
Wrong guest passwordLinuxFails with a hint about credentials
Powered on, VMware Tools not readyLinuxRetries, then fails
Two runs on the same VMLinuxSecond run waits 30 seconds, then runs
scriptTimeoutSec = 20 with sleep 60LinuxFails after 20 seconds, guest process terminated
Default 360 second timeoutLinux, WindowsFails after 360 seconds, guest process terminated
scriptWorkingDirectory set to a custom folderLinux, WindowsScript runs there, files cleaned up
Working directory that doesn’t existLinuxFails, the error names the folder
scriptTimeoutSec = -5LinuxFails with a clear message
Blank optional inputsLinux, WindowsDefaults used

And this is what a failure looks like. Here I asked for a PowerShell script on a Linux VM, so it stops at the type check, in a couple of milliseconds, and nothing touches the guest:

Failed Guest OS Script Engine run: a PowerShell script requested on a Linux VM stops at the script type check
Wrong script type for the guest OS: the run stops before anything is copied to the guest

Gotchas I ran into

A “$” in a value can break your password

The placeholder replacement used String.replace(regex, value). In JavaScript the replacement string is special: $$ becomes $ and $& becomes the matched text. So a password like Pa$$word reached the guest as Pa$word. Passing a function instead of a string inserts the value exactly:

var template = "password=[PASSWORD]";
var value = "Pa$$word$&";
var broken = template.replace(/\[PASSWORD\]/gi, value);
var fixed = template.replace(/\[PASSWORD\]/gi, function () { return value; });
System.log("broken: " + broken);
System.log("fixed: " + fixed);

Output:

broken: password=Pa$word[PASSWORD]
fixed: password=Pa$$word$&

Properties has no fromStringRepresentation

The old version had a branch for a “legacy” Resource Element format that called properties.fromStringRepresentation(). That method doesn’t exist on Properties, so the branch could never work. The real methods live on Server and take a StringRepresentation object, not a string. I removed the branch and made the timeout and working directory real inputs instead.

var props = new Properties();
System.log("Properties.fromStringRepresentation: " + typeof props.fromStringRepresentation);
System.log("Server.fromStringRepresentation: " + typeof Server.fromStringRepresentation);

Output:

Properties.fromStringRepresentation: undefined
Server.fromStringRepresentation: function

Known limitations

  • A powered-off VM is reported as “VM Tools is still not ready” after the retries, not as “powered off”. Check the power state first if the reason matters to you
  • Windows: the cmdANSI step leaves one empty vro-out-*.txt.clean file in the working directory per run
  • Linux: on timeout only the top-level shell is terminated. Commands the script started keep running
  • PowerShell output starts with a UTF-8 byte order mark. Strip \uFEFF before you parse it (the example above does)

Not affiliated with VMware by Broadcom. Provided as is: test it in a lab before you use it anywhere that matters.

Download from GitHub

Wrapping up

Running scripts inside a VM is one of those things every Orchestrator project needs sooner or later, and having one tested workflow for it saves a lot of copy-paste. Give it a VM, a script and credentials; check the exit code; and let it clean up after itself. If you hit a guest OS or a scenario I haven’t covered, tell me in the comments and I’ll add it to the test table.


Discover more from Cloud Blogger

Subscribe to get the latest posts sent to your email.

Enjoyed this post?

Was this helpful?

Leave a Reply