Skip to content

REST hosts and operations

Almost every product you’ll automate has a REST API, and the HTTP-REST plug-in is the most used plug-in after vCenter. It gives Orchestrator two objects. A REST host is a base URL with everything needed to reach it: timeouts, certificate, authentication, proxy. A REST operation is one call on that host, such as GET /api/vcenter/vm/{vm}, with placeholders for the parts that change.

The example API in this recipe is vCenter’s own REST API on vc01.vmw.lab, because every reader has one. You register it as a REST host, add two operations, try one with a built-in workflow, and then write an action that logs in, lists the VMs, and logs out, the pattern most token-based APIs follow.

Getting ready

  • A login to the Orchestrator Client with administrator rights. The configuration workflows need it.
  • The read-only vCenter account svc-vcfguide-ro@vsphere.local from recipe 4.5, and its password.
  • The action module com.vcfguide.chapter5 from recipe 5.1.
  • vco01.vmw.lab able to reach vc01.vmw.lab on TCP 443.

How to do it

Register the REST host

  1. Go to Library > Workflows, search with the tags http-rest and configuration, and run Add a REST host.
  2. On the Host Properties tab, enter:
Field Value
Name vc01-rest
URL https://vc01.vmw.lab
Connection timeout (seconds) 30, the default
Operation timeout (seconds) 60, the default
  1. Select the check box If set to true, the certificate is accepted silently and the certificate is added to the trusted store. Leave Support for parallel request executions cleared, and Redirect strategy at defaultRedirect (the other choices are alwaysRedirect and neverRedirect).
  2. On the Host Authentication tab, set Host’s authentication type to Basic. The list also offers NONE, OAuth 1.0, OAuth 2.0, Digest, NTLM and Kerberos. A User credentials tab appears: leave Session mode at Shared Session and fill in Authentication user name (svc-vcfguide-ro@vsphere.local) and Authentication password.
  3. Leave the Proxy Settings tab and the SSL tab as they are, and click Run.
  4. Go to Administration > Inventory > HTTP REST. The host vc01-rest is listed.
Run page of Add a REST host with the tabs Host Properties, Host Authentication, Proxy Settings and SSL. Host Properties: Name vc01-rest, URL https://vc01.example.com, Connection timeout (seconds) 30, Operation timeout (seconds) 60, the certificate check box selected, Support for parallel request executions cleared, Redirect strategy defaultRedirect.
Figure 5.4. The Host Properties page of the Add a REST host workflow, filled in.

Add two operations

  1. Search with the tags http-rest and configuration again, and run Add a REST operation. Select the host vc01-rest, and enter:
Field Value
Name Create session
Template URL /api/session
HTTP method POST
Content type application/json
  1. Run Add a REST operation once more, for the host vc01-rest, with Name Get VM, Template URL /api/vcenter/vm/{vm}, and HTTP method GET.
  2. In the inventory, expand vc01-rest. Both operations are under it.

The Template URL holds only the path, after the host’s URL. Anything in braces, such as {vm}, becomes a parameter you fill in when you call the operation.

Try an operation without code

  1. Search with the tag http-rest and run Invoke a REST operation. Select the operation Create session, leave the content empty, and click Run.
  2. On the run’s Variables tab, the status code is 201 and the response content is a quoted string of letters and digits. That’s a vCenter session token.
Figure 5.5. A REST operation run without code, and the session token it returned.

On 9.1.1, Invoke a REST operation (version 1.0.6) takes the operation (restOperation), up to 15 placeholder values (param_0 to param_14), content and defaultContentType for the request body, up to six extra headers (headerParam_0 to headerParam_5) and acceptHeaders. It returns statusCode and contentLength (both numbers), headers (Properties) and contentAsString.

Call the API from an action

  1. In Library > Actions, create the action listVcenterVms in com.vcfguide.chapter5, with one input, restHost of type REST:RESTHost, and the Return type Array/string:
com.vcfguide.chapter5/listVcenterVms
// Lists the VMs of a vCenter through its REST API.
// restHost is a REST host for the vCenter with Basic authentication.
function send(method, path, token) {
var request = restHost.createRequest(method, path, null);
request.setHeader("Accept", "application/json");
if (token) {
request.setHeader("vmware-api-session-id", token);
}
var response = request.execute();
System.debug(method + " " + path + " returned " + response.statusCode);
return response;
}
// Log in: Basic authentication on this call only, the token afterwards
var login = send("POST", "/api/session", null);
if (login.statusCode !== 201) {
throw "listVcenterVms: login to " + restHost.name + " failed with HTTP " + login.statusCode;
}
var token = JSON.parse(login.contentAsString);
var lines = [];
try {
var response = send("GET", "/api/vcenter/vm", token);
if (response.statusCode !== 200) {
throw "listVcenterVms: listing VMs failed with HTTP " + response.statusCode
+ ": " + response.contentAsString;
}
var vms = JSON.parse(response.contentAsString);
for (var i = 0; i < vms.length; i++) {
lines.push(vms[i].name + " (" + vms[i].power_state + ", " + vms[i].vm + ")");
}
System.log(vms.length + " VMs on " + restHost.name);
} finally {
// Always log out, so failed runs don't leave sessions behind
send("DELETE", "/api/session", token);
}
return lines;
  1. Run the action and pick vc01-rest for restHost. The result lists every VM with its power state and its ID, such as vm-1001.
  2. Run Invoke a REST operation again, this time for Get VM, with vm set to one of those IDs. It fails with an authentication error, 401, because Get VM needs a session token that this workflow doesn’t send. The next section explains why, and step 12’s action is the answer.
Figure 5.6. The action that logs in, lists the VMs, and logs out.
Needs a lab check. Checked on 9.1.1 with a transient host: createRequest takes null content for GET, and statusCode is a number, so !== works. Still to run against vCenter 9.1 with a service account: the full action, the DELETE call, and whether the Basic header on later calls gets in the way of the session token.

How it works

When a workflow or script runs a request, the plug-in builds the full URL from the host’s URL and the operation’s template, fills in the parameters, adds the host’s authentication, and sends it with its own HTTP client. The response comes back as a RESTResponse: statusCode is the HTTP status, contentAsString the body, and getAllHeaders() the headers. Nothing in the plug-in fails on a 404 or a 500. A response is a response, so check statusCode yourself, as the action does.

Hosts and operations live in the inventory. Add a REST host and Add a REST operation store their objects in Orchestrator’s database. They’re persistent: they survive restarts, every node in a cluster sees them, and they can go into a package. That’s the right home for an API that many workflows use. A script can also make a transient host that exists only while it runs (see There’s more).

Operations or createRequest? An operation is useful when people, or generated workflows, call the API without writing code. Get VM with its {vm} placeholder is exactly that. In a script, restHost.createRequest(method, path, content) is often simpler: you can build any path, and you don’t need an operation for each call.

Authentication on the host. The host’s authentication is added to every request it sends. That’s fine for APIs that accept Basic authentication on every call. vCenter, like many APIs, accepts it only on the login call and expects a session token on the rest, which is why the plain Invoke a REST operation in step 14 fails: it sends Basic authentication and no token. The action handles the token itself, and logs out in a finally block, so a failure halfway through doesn’t leave a session open on vCenter.

Shared or per-user session. With Shared Session, every request uses the account you entered, whoever runs the workflow. With Per User Session, the plug-in uses the credentials of the Orchestrator user running it, which only works when that user is also known to the API, for example through the same SSO. A workflow started by VCF Automation runs as a service user, not as the person who asked, so per-user hosts often fail there. Shared sessions with a least-privilege account are the safer default.

Certificates. Accepting the certificate in step 3 adds it to Orchestrator’s trust store, so every later call to that host is checked against it. When the API’s certificate is replaced, calls fail with a certificate error until you import the new one with Import a certificate from URL. It’s in the library folder SSL Trust Manager, with Import a trusted certificate from a file for hosts the server can’t reach directly, Import a certificate from URL with certificate alias when you want to find the entry again by name, the two proxy variants, and Delete a trusted certificate to clean up after a host is retired.

Back in vRO 5.5–7Import the REST host's certificate in the Configurator or Control Center, then run Add a REST host in the Java client and pick objects in its inventory tree.
In Orchestrator 9.xAccept the certificate in Add a REST host itself, or run Import a certificate from URL, and find the host under Administration > Inventory. A redirect strategy, OAuth 2.0, and Kerberos are options of the workflow.

There's more

A REST call without anything in the inventory. For a one-off call, a script can make a transient host. It isn’t saved, so nothing needs cleaning up:

Transient REST host
var template = RESTHostManager.createHost("vcfguide-transient");
var host = RESTHostManager.createTransientHostFrom(template);
host.url = "https://vc01.vmw.lab";
host.authentication = RESTAuthenticationManager.createAuthentication("Basic",
["Shared Session", user, password]);
var response = host.createRequest("POST", "/api/session", null).execute();
System.log("Login returned HTTP " + response.statusCode);

Read user and password from a configuration element (recipe 4.7), never from the script. Transient hosts can’t check the host name against the certificate or use a client certificate, and they don’t follow redirects for POST. Keep them for quick jobs inside one script: passing a transient host from one workflow element to another isn’t supported.

On 9.1.1, the first three lines of this script work as written. Leave out the authentication, and vCenter answers every call with 401 with a JSON body whose error_type is UNAUTHENTICATED, which is a quick way to check that Orchestrator can reach an API and trusts its certificate before you set up any account.

Needs a lab check. Still to check on 9.1.1: what a transient host does with a certificate that isn’t in the trust store.

Generate a workflow from an operation. Run Generate a new workflow from a REST operation, pick Get VM, give the workflow a name such as Get a vCenter VM, and pick the folder VCF Orchestrator Guide/Chapter 5. You get a workflow with an input for vm and outputs for the status and the content, ready to drop into other workflows. The workflow’s own inputs are operation, workflowName and category (the folder); namespace, element and use_xsd only matter for XML APIs with a schema. Its output, generatedWorkflow, points at the new workflow.

Calls without code that change each time. Invoke a dynamic REST operation takes a base URL, a method, and a path and stores nothing. Invoke a REST host with dynamic params and Invoke a REST operation with dynamic params reuse a stored host or operation and override some of its settings for one run.

Paging and limits. vCenter’s GET /api/vcenter/vm returns at most 4,000 VMs. On a larger vCenter, filter it with query parameters such as ?names=, ?folders=, or ?hosts=. Other APIs page their results. Either way, put the loop in the action, not in the workflow.

Time-outs. The Operation timeout limits how long one request may take. A slow report endpoint may need more than 60. Change it with Update a REST host, not by recreating the host, so the operations under it stay.

OAuth 2.0 and API tokens. For APIs that take a bearer token, choose OAuth 2.0 as the host’s authentication and enter the token, sent in the Authorization header. If the token expires, get a new one in the script and set the header yourself, as the action does with vCenter’s session ID.

Change a saved host’s credentials from a script. Tokens and service-account passwords get rotated, and a REST host that still holds the old one fails every call. A small workflow can put the new value on the saved host, so that whoever rotates the credential runs one workflow instead of clicking through Update a REST host on every server. Give it the inputs host (REST:RESTHost) and token (SecureString), and the output result (REST:RESTHost):

Update the token of a REST host
// ES5: replace the OAuth 2.0 token of a saved host, and send it in the Authorization header
if (host.authentication.type !== "OAuth 2.0") {
throw "[Update host token] " + host.name + " doesn't use OAuth 2.0, but " + host.authentication.type;
}
host.authentication = RESTAuthenticationManager.createAuthentication("OAuth 2.0",
[token, "Authorization header"]);
result = RESTHostManager.updateHost(host); // saves the change in the inventory
System.log("[Update host token] new token saved on " + host.name);

The second item in the array is the token sending strategy: Authorization header, or Query parameter, which puts the token in an oauth_token parameter of every URL, where web servers log it. Broadcom’s 8.x guide recommends the header, notes that the query parameter will be deprecated, and warns that the old one-item form, createAuthentication("OAuth 2.0", [token]), still means query parameter. host.authentication.rawAuthProperties[1] (or getRawAuthProperty(1)) tells you which one a host uses.

Needs a lab check. Run the token workflow on 9.1.1 against a REST host with OAuth 2.0 and check that Administration > Inventory > HTTP-REST shows the change, and record the order of rawAuthProperties for a Basic host with Shared Session.

See also