vRO VM Retrieval and Entitlement and Business Group Action Snippets

Mindwatering Incorporated

Author: Tripp W Black

Created: 06/11/2020 at 02:38 PM

 

Category:
VMWare
vRO - VCAC

List of vRO Module Action Samples from VMware collected here so don't have to search for them.

Get Entitlements of a Business Group:
// Custom Action - getBusinessGroups
// return - Array/vCACCAFE:Entitlement
// Action Inputs:
// businessGroup - vCACCAFE:Subtenant
// businessGroup.id - UUID
var host = vCACCAFEEntitiesFinder.getHostForEntity(businessGroup);
// CatalogOrgnizationReference __. BusinessGroup
var cc = host.createCatalogClient();
var ces = cc.getCatalogEntitlementService();

// search groups
var filters = [vCACCAFEFilterParam.equal("organization/subTenant/id", vCACCAFEFilterParam.string(businessGroup.id))];
var query = vCACCAFEOdataQuery.query().addFilter(filters);
var odataRequest = new vCACCAFEPageOdataRequest(query);
var entitlements = ces.get(host.tenant, odataRequest);
// loop entitlements for debug log
for each (var item in entitlements) {
System.log(item.name);
}
// return string to calling workflow
return entitlements;


Get Entitlements:
// Custom Action - getEntitlementNames
// return entitlements - Array/String - list of all the entitlement names
// start with empty array
var entitlements = [];

// Finding the CAFÉ host and the entitlements
var cafeHost = Server.findAllForType("vCACCAFE:VCACHost")[0];
var entitlementlist = vCACCAFEEntitiesFinder.findEntitlements(cafeHost);

// Storing the entitlement names in the variable entitlements
for ( i=0; i<entitlementlist.length; i++){
entitlements.push(entitlementlist[i].name)
}
// returning the variable with entitlements name
return entitlements;


Get Business Groups Names:
// Custom Action - getBusinessGroupNames
// return bgNames - Array/String - list of all the business group names
// start with empty array
var bgNames = [];

// Finding the CAFÉ host and then the Business Groups in that Tenant
var cafeHost = Server.findAllForType("vCACCAFE:VCACHost")[0];
var businessGroups = vCACCAFEEntitiesFinder.getBusinessGroups(cafeHost);

// Storing the names of all the Business Groups in the variable bgNames
for (i=0; i < businessGroups.length; i++) {
bgNames.push(businessGroups[i].name);
}

// returning the variable bgNames
return bgNames;


Get Business Group Object By Name:
// Custom Action - getBusinessGroup
// returns finalBG/vCACCAFE:Subtenant / vCACCAFE:BusinessGroup
// Action Input:
// host:vCACCAFE:VCACHost
// bgName:String
businessGroups = vCACCAFEEntitiesFinder.getBusinessGroups(vCACACAFEHost);
// Locate and return group in list of groups
for(i=0; i< businessGroups.length;i++){
if (bgName == businessGroups[i].name){
var finalBG = businessGroups[i];
break;
}
}
return finalBG;

Note:
To do a lowercase match update the if comparison to:
if (bgName.toLowerCase() == businessGroups[i].name.toLowerCase()){


Is User in Business Group:
// Custom Action - isUserInBusinessGroup
// return alreadyExists:boolean
// Action Input:
// bg / vCACCAFE:BusinessGroup
// userName / String
var userNames = finalBG.getUsers();
var size = 0;
if (userNames){
size = userNames.length;
}
var alreadyExists = false;

if (size) {
// Checking to see if the user already exists in the Business group
for (var j = 0 ; j < size ; j++ ) {
if (userName == userNames[j]) {
System.log("User " + userName + " is member of Business Group " + finalBG.getName() + ".");
alreadyExists = true;
break;
}
}
}
return alreadyExists;


Is User in Entitlement:
// Custom Action - isUserInBusinessGroup
// return alreadyExists:boolean
// Action Input:
// entitlement / vCACCAFE:Entitlement
// userName / String
var alreadyExists = false;
for (var j = 0 ; j < entitlement.getPrincipals().length ; j++ ) {
if (userName == entitlement.getPrincipals()[j].getRef()) {
System.log("User " + userName + " is member of entitlement " + entitlement.getName() + ". ");
alreadyExists = true;
break;
}
}
return alreadyExists;



_______________________


Workflow Snippets:

Find if User is Member of AD group, 'someUserGroup':
var grpNmChk = "SomeUserGroup";
var adGrps = new Array();
var alreadyMbr = false;
adGrps = usrObj.getArrayAttribute('memberOf');
for each (dn in adGrps) {
System.log("Group dn " + dn);
// check if matches group name
if (dn ==grpNmChk) {
alreadyMbr = true;
break;
}
}
return alreadyMbr;


Add User to group:
// In:
// userName / string - name off of form
// bGrp / vCACCAFE:BusinessGroup

try {
userNames[size] = userName;
bGrp.setUsers(userNames);
if( !bGrp.activeDirectoryContainer){
bGrp.setActiveDirectoryContainer("");
}
// add the user to Business Group
System.log("Adding user, " + userName + ", to Business Group " + bGrp.getName() + "...");
vCACACAFEHost.createInfrastructureClient().getInfrastructureBusinessGroupsService().update(bGrp);
System.log("User, " + userName + ", added to Business Group, " + bGrp.getName()) + ".";
}
catch(errorCode){
// In case of any error throw the error
System.error(errorCode);
throw errorCode;
}


Add User to Entitlement:
// In:
// userName / string - user id/name off of form or previous workflow out
// bgName/ string - group name off of form or previous workflow out
// entitlementNames / string - the selected names from the form or previous workflow out

try {
// getting a list of all the entitlements
entitlementslist = vCACCAFEEntitiesFinder.findEntitlements(vCACACAFEHost);

// Running the loop to get the entitlement which user specified
// entitlementnames holds all the entitlement names which user specified
// entitlementlist holds the list of all the entitlements.
// note entitlementnames is an array of strings while entitlementslist is an array of entitlement object
for( i =0; i<entitlementnames.length; i++){
for( j=0; j<entitlementslist.length; j++){
if ( entitlementNames[i] == entitlementslist[j].name){
entitlement = entitlementslist[j];
break;
}
}
// at this stage we found our entitlement object
// validating the object
System.getModule("com.vmware.library.vcaccafe.util").validateObject(entitlement, "Entitlement");

// Getting the CAFE host object for the entitlement
var host = vCACCAFEEntitiesFinder.getHostForEntity(entitlement);
// Getting the entitlement service object
var client = host.createCatalogClient().getCatalogEntitlementService();

var alreadyExists = false;

// Checking to see if the user already exists in the entitlement
for (var j = 0 ; j < entitlement.getPrincipals().length ; j++ ) {
if (userName == entitlement.getPrincipals()[j].getRef()) {
System.warn("User " + userName + " is already assigned to the entitlement "+entitlement.getName()+". The user will be skipped.");
alreadyExists = true;
break;
}
}
if (!alreadyExists) {
// This means user is not already in Entitlement
var principal = new vCACCAFECatalogPrincipal();
principal.setType(vCACCAFEPrincipalType.USER);
principal.setRef(userName);
principal.setTenantName(host.tenant);
System.getModule("com.vmware.library.vcaccafe.util").addElementToList(entitlement, "getPrincipals", principal);
System.log("Assigning user to entitlement " + entitlement.getName() + "...");
client.update(entitlement);
System.log("User assigned to entitlement " + entitlement.getName());
}
}
catch(errorCode){
System.error(errorCode);
throw errorCode;
}



Find AD Group:
var grpNm = "GrpToFind";
var grpUObj = Server.findAllForType("AD:UserGroup", grpNm); // find group by name, but only if a user type group
var grpObj = Server.findAllForType("AD:Group", grpNm); // find any group



Find AD User:
var usrNm = "tom.test@mydomain.com";
var usrObj = Server.findAllForType("AD:User", usrNm);
... or ...
var usrObj = ActiveDirectory.searchExactMatch("AD:User", usrNm);
... or ...
var svrAD= System.getModule("mydomain.activeDirectory").getAdHost(domain);
System.debug(adHost);
var usrObjs = ActiveDiretory.search("User", usrNm, svrAD);
if (usrObjs == null) {
return [];
}
System.log("Users objects found: " + usrObjs.length);

Get Users:
var svrAD= System.getModule("mydomain.activeDirectory").getAdHost(domain);
var usrObjs = ActiveDiretory.search("User", "", svrAD);
if (usrObjs == null) {
return [];
}
System.log("Users objects found: " + usrObjs.length);



Find a Computer (Name):
var vmNm = "Josh-02";
var vmObjs= ActiveDirectory.search("ComputerAD", vmNm, svrAD); // this can return more than one object for the name
System.log("Computer objects found: " + vmObjs.length);



Find the vCenter (VC):
// load up the vCACCAFE Literal Map
var vData = vraVm.resourceData;
// get vCenter instanceUuid
var vcID = vData.get("endpointExternalReferenceId").value;
// cross check with SDKConnections which includes all connections to vCenters
var vcConns = VcPlugin.allSdkConnections;
for each (conn in vcConns) {
// Make sure we set "vc" to the vCenter connection that matches the resourceData endpointExternalReferenceId
if (conn.about.instanceUuid == vcID){
var vc = conn;
} else {
System.debug('vcID did not match the conn instanceUuid.');
}
}
if (vc) {
...
} else {
// no VC using vcID
System.warn('VC connection not found with vcID: ' + vcID;
}


Get a VM via VCAC Server Object:
Input:
vmName (String)

Ouput:
vCACVM (VCAC:Machine)

Script:
vCACVM = null;
if(vmName == null) {
System.warn('VM Name no provided.');
}
if(vmName == '') }
System.warn('VM Name no provided.');
}
var vCACVMs = Server.findAllForType("vCAC:VirtualMachine", "VirtualMachineName eq '" + vmName + "' and IsManaged eq true");
if (vCACVMs == null) {
System.warn('No VMs returned with name' + vmName + '.');
return vCACVM;
} else {
if (vCACVMs[0] == undefined || vCACVMs[0] == null) {
System.warn('No VMs returned with name' + vmName + '.');
return vCACVM;
} else {
// check length because we can have not undefined and length of 0 somehow still
if ((vCACVMs[0] != null || vCACVMs[0].length == 0) {
System.warn('No VM returned with name' + vmName + '.');
return vCACVM;
} else {
// have VM
vCACVM = vCACVMs[0];
return vCACVM;
}
}
}


Get a VM via the data map External_Reference_ID (Managed Object Reference - MoRef):
// load up the vCACCAFE Literal Map
var vData = vraVm.resourceData;
// retrieve the MoRef ID
vm vmMoRef = vData.get("EXTERNAL_REFERENCE_ID").value;
// create the vm managed object
var vmManagedObject = new VcManagedObjectReference();
vmManagedObject.type = "VirtualMachine";
vmManagedObject.value = vmMoRef;
var vm = VcPlugin.convertToVimManagedObject(vc , vmManagedObject);
if (vm) {
System.debug('Found VM: ' + vm.name;
} else {
System.debug('VM Not Found with MoRef ID: ' + vmMoRef;
}


Get a VM via the data map External_Reference_ID/MoRef ID, but use the vc.getAllVirtualMachines via filtered search
// load up the vCACCAFE Literal Map
var vData = vraVm.resourceData;
// retrieve the MoRef ID
vm vmMoRef = vData.get("EXTERNAL_REFERENCE_ID").value;
// build the filter
var XPath = "xpath:id='"+ vmMoRef +"'";
// get the vc
var vcID = vData.get("endpointExternalReferenceId").value;
// cross check with SDKConnections which includes all connections to vCenters
var vcConns = VcPlugin.allSdkConnections;
for each (conn in vcConns) {
// Make sure we set "vc" to the vCenter connection that matches the resourceData endpointExternalReferenceId
if (conn.about.instanceUuid == vcID) {
var vc = conn;
}
}
if (vc) {
// get the vm
var vm = vc.getAllVirtualMachines(null, XPath)[0];
if (vm) {
System.debug('Found VM: ' + vm.name;
} else {
System.debug('VM Not Found with MoRef ID: ' + vmMoRef;
}
} else {
// no VC using vcID
System.warn('VC connection not found with vcID: ' + vcID;
}


Get a VM (or other deployed resource) via the IAAS/vRA request:
/*
Action Name: getResourcesByRequestID
Input: vCACCAFEHost - vCACCAFE:VCACHost
Input: requestId - String
Output: vResArr- Array/vCACCAFECatalogResource
Description: Get recourses from catalog request
*/

// get the service
var cClient = vCACCAFEHost.createCatalogClient();
var reqSvc = cClient.getCatalogConsumerRequestService();

// get the resources array - (array of vCACCAFECatalogResource)
var vResArr = reqSvc.getResourcesProvisionedByRequest(requestId, null).getContent();

// print out the resource IDs and Names for debug log
for (var i = 0; i < vResArr.length; i++){
System.debug("Id: " + vResArr[i].id);
System.debug("Name: " + vResArr[i].name);
}
return vResArr;



Get a VM (or other deployed resources) from a passed vRA Request object:
/*
Action Name: getResourcesByRequest
Input: vCACCAFEHost - vCACCAFE:VCACHost
Input: cRequest- vCACCAFE:CatalogItemRequest (from vRA)
Output: vResArr- Array/vCACCAFECatalogResource
Description: Get recourses from catalog request. Contains only 1 resource (the ID) until the provision is complete.
Note: This performs badly once the number of requests is in the 10,000s
*/
var vResAllArr = vCACCAFEEntitiesFinder.findCatalogResources(host);
var reqResArr = new Array();
for each (var resource in vResAllArr) {
if (resource.requestId === cRequest.id) {
reqResArr.push(resource);
}
}

if (reqResArr.length === 0) {
System.warn('Catalog resources not found for the given request.' + cRequest.id );
}

return catalogResources;

__________________

// Code to get VMs from resources from vResArr - Array/vCACCAFECatalogResource, from above action
var VMLst = [];
var vcacVMLst = [];

for (i=0; i < vResArr.length; i++) {
if (vResArr[i].resourceTypeRef.getLabel() === "Virtual Machine") {
System.debug("Decide component groups-Component VM name = " + vResArr[i].name);
var vCacVm = Server.findForType("vCAC:VirtualMachine", vResArr[i].providerBinding.getBindingId() );
vcacVMLst.push(vCacVm);
vmNmLst.push(vResArr[i].name);
} else {
System.debug('Not VM resource: ' + vResArr[i].name);
}
}

Get a VM from a passed request ID using the web API instead of the vRO objects:
Notes:
You can do this w/ or w/o a REST host. If you set-up a REST host, you don't have to handle authentication.
Syntax: https://"+VRA+"/catalog-service/api/consumer/requests/"+requestID+"/resourceViews
Input: reqID - String
Input: restHost - REST:RestHost
Input: authToken - String

var childVMs = [];

if (reqID == null || reqID == '') {
return childVMs;
}
var operationUrl = ('/catalog-service/api/consumer/requests/' + reqID + '/resourceViews');
var requestType = "GET";
var retrycount = 5;
var requestContentType = "application/json";
var request = att_resthost.createRequest(requestType, operationUrl, {} );
request.contentType = requestContentType;
request.setHeader("Accept", "application/json");
// not needed if using a vRO configured REST host and you set-up authentication
// request.setHeader("Authorization","Basic " + authToken);

for (var i=1; i< retrycount + 1; i++) {
try {
response = request.execute();
} catch (e) {
System.error(e);
System.sleep(10000);
continue;
}
strresponse = response.contentAsString;
System.log("Response Status Code: " + response.statusCode);
System.log("Content As String: " + strresponse);

jsonresponse = JSON.parse(strresponse);
System.log("Returned Data: " + jsonresponse.responseObject.data);
if (jsonresponse.responseObject.data != "") {
// Parse for VMs by desired attribute (e.g. Hostname, ID, etc.)
....

}
break;
}




Get a VM (or other deployed resources) from a passed vRA Catalog Request:
/*
Action Name: getResourcesByCatalogRequest
Input: vCACCAFEHost - vCACCAFE:VCACHost
Input: cRequest- vCACCAFE:CatalogItemRequest (from vRA)
Output: vResArr- Array/vCACCAFECatalogResource
Description: Get recourses from catalog request. Contains only 1 resource (the ID) until the provision is complete.
Note: This performs badly once the number of requests is in the 10,000s
*/
var filter = "VirtualMachineProperties/any(p: " + "(p/PropertyName eq '__Cafe.Root.Request.Id' and p/PropertyValue eq '" + cRequest + "')" + " )";

System.debug("VCACCafe Host is " + vCACCAFEHost);
var vmEntities = vCACEntityManager.readModelEntitiesBySystemQuery(vCACCAFEHost.id, "ManagementModelEntities.svc", "VirtualMachines", filter);
if (vmEntities != null && vmEntities.length > 0) {
System.debug("vmEntities.length is " + vmEntities.length);
for each (var iaasVmEntity in vmEntities) {
System.debug("VCAC iaasVmEntity (vCAC:Entity) is " + iaasVmEntity);
var vCACVM = iaasVmEntity.getInventoryObject();
var vCACVMId = iaasVmEntity.id;
System.debug("vCACVM name: " + vCACVM.name );
return vCACVM;
}
break;
}


Get all VMs connected to vRO:
(This is MORE than the vRO managed machines. This is also a good way to get a VC:VirtualMachine from a VCAC:VirtualMachine.)

var vCenters=VcPlugin.allSdkConnections;
var vcVMs = [];

for each (vCenter in vCenters) {
var vms = vCenter.allVirtualMachines:
for each (vCACVM in vms) {
System.log(vCACVM.name);
// get vc:virtualmachine
vCenterVm = vCenter.searchIndex.findByUuid(null, vCACVM.vmUniqueID, true, true);
}
}

Get all VMs Managed in vRO:
Input: <none>
Output: vCACVMs - vCAC:VirtualMachine (Array)

var vCACVM = null;
var vmNm = '';
var vmIP = '';
var vCACVMs = Server.findAllForType("vCAC:VirtualMachine", "IsManaged eq true");
// loop VMs for debug log (output is already ready) - remove rest below if not desired
var i =0;
for(i in vCACVMs) {
var vCACVM = vCACVMs[i];
if (vCACVM !=null) {
vmNm = vCACVM.virtualMachineName;
if (vmNm !='') {
try {
vmIP = System.resolveIpAddress(vmNm);
} catch(e) {
vmIP = '';
}
System.debug(',' + vmNm + ',' + vmIP);
}
}
}


Get VM's parent Catalog Resource:
Input: vCACCAFEHost - vCACCAFE:VCACHost
Input: virtualMachine - VC:VirtualMachine

var vmParentResource = null;
var name = virtualMachine.virtualMachineName;
var id = virtualMachine.virtualMachineID;
var catalogResources = vCACCAFEEntitiesFinder.findCatalogResources(cafeHost, name);

for each (var resource in catalogResources) {
if (resource.providerBinding.getBindingId() === id) {
vmParentResource = resource;
}
}


Get All VM's for a Parent Catalog Resource
Input: vCACCAFEHost - vCACCAFE:VCACHost
Input: vmParentResource - vCACCAFE:CatalogResource
Note: This performs badly once the number of requests is in the 10,000s
(It's the findCatalogResources action that doesn't scale well.)

var childResources = [];
var parentResourceId = vmParentResource.id;
var allResources = vCACCAFEEntitiesFinder.findCatalogResources(vCACCAFEHost);

for each (var r in allResources) {
if (r.parentResourceRef && r.parentResourceRef.getId() === parentResourceId) {
if (r.resourceTypeRef.getLabel() == "Virtual Machine") {
System.debug('vm added: ' + r.name);
childResources.push(r);
} else {
// skip, not vm
}
}
}
// return childResources;


Get Catalog Request ID for VM:
Input: vCACHost - vCAC:VCACHost
Input: vCACVM - vCAC:VirtualMachine

var vmEntity = System.getModule("com.vmware.library.vcac").getVirtualMachineEntity( vCACHost, vCACVM );
var requestId = getVmEntityPropertyValue( vCACHost, vmEntity, "__Cafe.Root.Request.Id");
return requestId;

function getVmEntityPropertyValue(vCACHost, vmEntity, propertyName) {
var virtualMachinePropertiesEntities = vmEntity.getLink(vCACHost, "VirtualMachineProperties");
for each (var virtualMachinePropertiesEntity in virtualMachinePropertiesEntities) {
if (virtualMachinePropertiesEntity.getProperty("PropertyName") == propertyName) {
return virtualMachinePropertiesEntity.getProperty("PropertyValue");
}
}
return null;
}



Get vCenter VM from VMEntity for a VM:
Input: vCACHost - vCAC:VCACHost
Input: vCACVM - vCAC:VirtualMachine

//var vmEntity = System.getModule("com.vmware.library.vcac").getVirtualMachineEntity( vCACHost, vCACVM )
var vmEntity = vCACVM.getEntity();

// parameters for sdkConnection call
var searchDC = null;
var searchVMs = true; // only VMs
var searchUUID = true; // false - not BIOS id

// get vmEntity UUID
// not same as vRA UUID in payload: VirtualMachine.Admin.UUID
var vmID = vEntity.getProperty("VMUniqueID");
// get vmEntity MOID
var vmMOID = vEntity.getProperty("ExternalReferenceId");
if (vmID == vmMOID) {
System.debug('MOID and UUID match: ' + vmID + '.');
} else {
System.debug('MOID: ' + vmMOID + ', UUID: ' + vmID + '.');
}

try {
sdkConnections = VcPlugin.allSdkConnections;
if (sdkConnections.length > 0) {
for (var i = 0; i < sdkConnections.length; i++) {
vCenterVm = sdkConnections[i].searchIndex.findByUuid( searchDC, vmID, searchVMs, searchUUID );
if (vCenterVm) {
vCenterVMNm = sdkConnections[i].name;
vCenterNm = sdkConnections[i].name;
log.log("Found vcenter virtual machine '" + vCenterVMNm + "' on vCenter '" + vCenterNm + "'");
found = true;
break;
}
}
} else {
System.log('No vCenter server endpoints were found.');
}
if (!found) {
System.log('The vCenter virtual machine could not be found with instance uuid:' + vmID + '.');
}
} catch (e) {
System.error('Action failed. Error:', e);
}









previous page