The vAPI plug-in, vSphere tags and content libraries
vCenter has two APIs. The vSphere plug-in (recipe 8.1) wraps the older one, the vSphere Web Services API: VMs, hosts, clusters, tasks. Newer features were only ever added to the other one, the vSphere Automation API, the REST API at https://<vcenter>/api: tags and categories, content libraries, and more. Orchestrator reaches it with the vAPI plug-in.
Tagging VMs and deploying from a content library are two of the things people most often ask Orchestrator to do, for backup policies, NSX security groups, and VM templates kept in one place. This recipe does both.
Getting ready
vc01.vmw.labregistered in the vSphere plug-in (recipe 1.9), and an account on it that may create tags and deploy VMs. For a lab,administrator@vsphere.localworks; in production, use a service account with the Tagging and Content Library privileges it needs.- A content library with an OVF template, here Images with
ubuntu-24.04-server-cloudimg-amd64. - The action module
com.vcfguide.chapter8withwaitForTask(recipe 8.1), and a test VM you can tag,vcfguide-test-01.
How to do it
A. Add the vAPI endpoint
Section titled “A. Add the vAPI endpoint”- Run Add vAPI endpoint (Library > VAPI) with endpointUrl
https://vc01.vmw.lab/api, the account and its password, and Use secure connection set to Yes. The workflow adds the endpoint and imports the API’s metamodel, the description of its services, from which the plug-in builds its scripting classes. - Check it: run List all tagging categories (Library > VAPI > Examples > vSphere) with the new endpoint. It returns the categories that exist in vCenter, often a few that VCF itself created.
Inventory > VAPI with the endpoint https://vc01.vmw.lab/api selected.
B. Find the right endpoint for a VM
Section titled “B. Find the right endpoint for a VM”- A script that tags a VM must call the vAPI endpoint of that VM’s vCenter. With several vCenters, calling the wrong one fails with an error that looks like a permissions problem (see How it works). Create the action
getVapiEndpointincom.vcfguide.chapter8, with the inputvcObject(Any) and the return typeVAPI:VAPIEndpoint:
if (!vcObject) { throw "[VCFG][getVapiEndpoint] vcObject is required";}// The plug-in's connection name is the vCenter's SDK URL, such as https://vc01.vmw.lab:443/sdkvar sdk = vcObject.sdkConnection ? vcObject.sdkConnection : vcObject;var host = String(sdk.name).replace(/^https?:\/\//, "").replace(/[:\/].*$/, "");var url = "https://" + host + "/api";var endpoint = VAPIManager.findEndpoint(url);if (!endpoint) { throw "[VCFG][getVapiEndpoint] no vAPI endpoint for " + host + ": add " + url + " with Add vAPI endpoint";}return endpoint;C. Tag a VM
Section titled “C. Tag a VM”- Create
ensureVmTag, with the inputsendpoint(VAPI:VAPIEndpoint),categoryNameandtagName(string), and the return typestring. It returns the tag’s ID, and creates the category and the tag when they don’t exist yet:
if (!endpoint || !categoryName || !tagName) { throw "[VCFG][ensureVmTag] endpoint, categoryName and tagName are required";}var client = endpoint.client();try { var categories = new com_vmware_cis_tagging_category(client); var tags = new com_vmware_cis_tagging_tag(client);
// Find the category by name, or create it var categoryId = null; var categoryIds = categories.list(); for (var i = 0; i < categoryIds.length && !categoryId; i++) { if (categories.get(categoryIds[i]).name === categoryName) { categoryId = categoryIds[i]; } } if (!categoryId) { var categorySpec = new com_vmware_cis_tagging_category_create__spec(); categorySpec.name = categoryName; categorySpec.description = "Created by a workflow"; categorySpec.cardinality = "SINGLE"; // one tag of this category per VM categorySpec.associable_types = ["VirtualMachine"]; categoryId = categories.create(categorySpec); System.log("[VCFG][ensureVmTag] created category " + categoryName); }
// Find the tag in that category, or create it var tagIds = tags.list_tags_for_category(categoryId); for (var t = 0; t < tagIds.length; t++) { if (tags.get(tagIds[t]).name === tagName) { return tagIds[t]; } } var tagSpec = new com_vmware_cis_tagging_tag_create__spec(); tagSpec.name = tagName; tagSpec.description = "Created by a workflow"; tagSpec.category_id = categoryId; var tagId = tags.create(tagSpec); System.log("[VCFG][ensureVmTag] created tag " + categoryName + "/" + tagName); return tagId;} finally { client.close();}- Create
tagVm, with the inputsvm(VC:VirtualMachine),categoryNameandtagName, and the return typevoid. vAPI doesn’t know the vSphere plug-in’s objects; it names an object by its type and managed object ID, in acom_vmware_vapi_std_dynamic__ID:
if (!vm) { throw "[VCFG][tagVm] vm is required";}var chapter8 = System.getModule("com.vcfguide.chapter8");var endpoint = chapter8.getVapiEndpoint(vm);var tagId = chapter8.ensureVmTag(endpoint, categoryName, tagName);
// vAPI names a vSphere object by its type and managed object ID, such as VirtualMachine vm-2290var objectId = new com_vmware_vapi_std_dynamic__ID();objectId.type = "VirtualMachine";objectId.id = vm.id;
var client = endpoint.client();try { new com_vmware_cis_tagging_tag__association(client).attach(tagId, objectId);} finally { client.close();}System.log("[VCFG][tagVm] " + vm.name + " tagged " + categoryName + "/" + tagName);- Create
getVmTags(inputvm, return typeArray/string) to read them back ascategory/tag, anduntagVm(inputsvm,categoryName,tagName) to remove one:
if (!vm) { throw "[VCFG][getVmTags] vm is required";}var endpoint = System.getModule("com.vcfguide.chapter8").getVapiEndpoint(vm);var objectId = new com_vmware_vapi_std_dynamic__ID();objectId.type = "VirtualMachine";objectId.id = vm.id;
var client = endpoint.client();try { var tags = new com_vmware_cis_tagging_tag(client); var categories = new com_vmware_cis_tagging_category(client); var tagIds = new com_vmware_cis_tagging_tag__association(client).list_attached_tags(objectId); var result = []; for (var i = 0; i < tagIds.length; i++) { var tag = tags.get(tagIds[i]); result.push(categories.get(tag.category_id).name + "/" + tag.name); } return result;} finally { client.close();}if (!vm || !categoryName || !tagName) { throw "[VCFG][untagVm] vm, categoryName and tagName are required";}var endpoint = System.getModule("com.vcfguide.chapter8").getVapiEndpoint(vm);var objectId = new com_vmware_vapi_std_dynamic__ID();objectId.type = "VirtualMachine";objectId.id = vm.id;
var client = endpoint.client();try { var tags = new com_vmware_cis_tagging_tag(client); var categories = new com_vmware_cis_tagging_category(client); var association = new com_vmware_cis_tagging_tag__association(client); var attached = association.list_attached_tags(objectId); for (var i = 0; i < attached.length; i++) { var tag = tags.get(attached[i]); if (tag.name === tagName && categories.get(tag.category_id).name === categoryName) { association.detach(attached[i], objectId); System.log("[VCFG][untagVm] removed " + categoryName + "/" + tagName + " from " + vm.name); return; } } System.log("[VCFG][untagVm] " + vm.name + " doesn't have " + categoryName + "/" + tagName);} finally { client.close();}- Test them on
vcfguide-test-01:tagVmwithvcfguide-backupandgold, thengetVmTags(it returnsvcfguide-backup/gold), thentagVmagain withsilver. The second tag fails with Tagging cardinality violation, because the category allows one tag per VM. To move a VM from gold to silver,untagVmthe old tag first.
D. Deploy a VM from a content library
Section titled “D. Deploy a VM from a content library”- Create
deployFromLibrary, with the inputslibraryName,itemName,vmName(string),folder(VC:VmFolder),resourcePool(VC:ResourcePool) anddatastore(VC:Datastore), and the return typeVC:VirtualMachine. It looks the template up by name, deploys it thin provisioned, and hands back the vSphere plug-in’s object for the new VM:
if (!libraryName || !itemName || !vmName || !folder || !resourcePool || !datastore) { throw "[VCFG][deployFromLibrary] all inputs are required";}var endpoint = System.getModule("com.vcfguide.chapter8").getVapiEndpoint(folder);var client = endpoint.client();var vmId = null;try { // Find the library, then the item in it, by name var libraries = new com_vmware_content_library(client); var items = new com_vmware_content_library_item(client); var libraryId = null; var libraryIds = libraries.list(); for (var i = 0; i < libraryIds.length && !libraryId; i++) { if (libraries.get(libraryIds[i]).name === libraryName) { libraryId = libraryIds[i]; } } if (!libraryId) { throw "[VCFG][deployFromLibrary] content library " + libraryName + " not found"; } var itemId = null; var itemIds = items.list(libraryId); for (var j = 0; j < itemIds.length && !itemId; j++) { var item = items.get(itemIds[j]); if (item.name === itemName) { if (item.type !== "ovf") { throw "[VCFG][deployFromLibrary] " + itemName + " is a " + item.type + " item, not an OVF template"; } itemId = itemIds[j]; } } if (!itemId) { throw "[VCFG][deployFromLibrary] " + itemName + " not found in " + libraryName; }
// Where the VM goes: managed object IDs from the vSphere plug-in objects var target = new com_vmware_vcenter_ovf_library__item_deployment__target(); target.resource_pool_id = resourcePool.id; target.folder_id = folder.id;
var spec = new com_vmware_vcenter_ovf_library__item_resource__pool__deployment__spec(); spec.name = vmName; spec.accept_all_EULA = true; spec.default_datastore_id = datastore.id; spec.storage_provisioning = "thin";
System.log("[VCFG][deployFromLibrary] deploying " + libraryName + "/" + itemName + " as " + vmName); var result = new com_vmware_vcenter_ovf_library__item(client).deploy(null, itemId, target, spec); if (!result.succeeded) { throw "[VCFG][deployFromLibrary] deploy failed: " + VAPIManager.stringifyDataValue(result.error); } vmId = result.resource_id.id;} finally { client.close();}
// Hand back the vSphere plug-in object, so the caller can power it on, tag it, and so onvar vms = VcPlugin.getAllVirtualMachines(null, "xpath:name='" + vmName + "'");for (var k = 0; k < vms.length; k++) { if (vms[k].id === vmId && vms[k].sdkConnection.id === folder.sdkConnection.id) { System.log("[VCFG][deployFromLibrary] " + vmName + " is " + vmId); return vms[k]; }}throw "[VCFG][deployFromLibrary] deployed " + vmId + " but the vSphere plug-in doesn't see it yet";- In VCF Orchestrator Guide/Chapter 8, create the workflow Deploy a VM from a content library, with the six inputs of the action plus
tagCategoryandtagName, and the outputvm. Its schema is the action, then a scriptable task that callstagVmwhentagCategoryisn’t empty. Run it with the libraryImages, the templateubuntu-24.04-server-cloudimg-amd64, the namevcfguide-test-02, and the tagvcfguide-backup/silver. The deploy is a long call: the run waits on it, a few minutes for a 4 GB template.
Completed run of Deploy a VM from a content library: Logs tab with deploying Images/ubuntu-24.04-server-cloudimg-amd64 as vcfguide-test-02, vcfguide-test-02 is vm-… and vcfguide-test-02 tagged vcfguide-backup/silver.
endpoint.client() with no arguments uses the endpoint’s stored account. A second tag in a SINGLE category fails with Tagging cardinality violation. Deploying the 4 GB Ubuntu template took about two and a half minutes and gave a thin-provisioned VM. Each tagVm call took about ten seconds, mostly in opening the vAPI sessions.How it works
Two APIs, two plug-ins. The vSphere plug-in speaks the Web Services (SOAP) API and gives you VC: objects. The vAPI plug-in speaks the Automation API and gives you classes named after its services: com.vmware.cis.tagging.Tag becomes com_vmware_cis_tagging_tag, and a nested type such as TagAssociation becomes com_vmware_cis_tagging_tag__association, with a double underscore. The vSphere Automation API reference lists every service.
Objects cross by ID. vAPI calls take and return IDs, not plug-in objects. A VM goes in as a DynamicID of type VirtualMachine and its managed object ID, vm.id; a folder, resource pool or datastore goes in as its id. Coming back, deployFromLibrary turns the new VM’s ID into a VC:VirtualMachine again, checking the vCenter too, because two vCenters can both have a vm-2291.
Wrong vCenter, misleading error. Broadcom KB 384226 describes a tagging workflow failing with cis.tagging.unauthorized.error, although the account could tag the VM in the vSphere Client. The workflow was calling another vCenter, where that VM doesn’t exist. getVapiEndpoint takes the vCenter from the VM itself, so a script can’t make that mistake.
Sessions cost time. Every endpoint.client() opens a session with vCenter, and every call is an HTTPS request. Close each client in finally, as these actions do, or the sessions pile up. When you tag hundreds of VMs, open one client and reuse it for the whole loop rather than calling tagVm once per VM.
Metamodels and endpoints are separate. The metamodel gives Orchestrator the scripting classes; the endpoint is the connection. An Orchestrator keeps at most 20 metamodels, and the library workflow Add vAPI endpoint imports one every time it runs. On a server with many vCenters, import a metamodel once and add the other vCenters with VAPIManager.addEndpoint() from your own setup workflow (recipe 9.4): in the lab, an endpoint added this way used the classes of a metamodel imported earlier.
There's more
Tags drive other products. Backup products can protect VMs by vSphere tag, so a provisioning workflow that tags each new VM by its service level puts it in the right backup job without anyone touching the backup tool. NSX security tags are a different thing from vSphere tags; recipe 8.4 sets those through the NSX API.
See also
- 8.1 Workflows against vCenter, for the vSphere plug-in and
waitForTask. - 8.2 Provisioning a VM from a template, for cloning from a VM template instead.
- 8.4 NSX automation, for NSX tags.
- 7.4 Tags, for Orchestrator’s own workflow tags, a different thing.
- Broadcom KB 384226, Unauthorized error when attaching tags to vCenter VMs via Aria Orchestrator workflow.
