vRO Action to return virtual machines with a specific tag

I am a huge fan of tags in vSphere.   Meta data is the king for modular control and policy based administration.   I wrote a action for a lab I presented at VMUG sessions.   It takes the name of a tag as a string and returns the names of all virtual machines as an array of strings.  It does require a VAPI endpoint setup as explained here: (http://www.thevirtualist.org/vsphere-6-automation-vro-7-tags-vapi-part-i/) Here it is:

 

Return Type: Array/String (Could be Array VC:VirtualMachine)

Parameter: tagNameToMatch string

Code: return_vm_with_tag

 // array to hold the vm names
 var vmsWithSpecificTag = new Array();
 // VAPI connection
 var endpoints = VAPIManager.getAllEndpoints();
 //Use the first returned endpoint to gather information
 var client = endpoints[0].client();
 //var client = end.client(); 
 //Get associations
 var tagging = new com_vmware_cis_tagging_tag__association(client);
 //Get tags
 var tagMgr = new com_vmware_cis_tagging_tag(client);
 //Create object to hold VM
 var objId = new com_vmware_vapi_std_dynamic__ID() ;

//Get all virtual machines
 vms = System.getModule("com.vmware.library.vc.vm").getAllVMs();
 //loop though virtual machines
 for each (vm in vms)
 {
 // assign VM data to object
 objId.id = vm.id;
 // assign VM data to object
 objId.type = vm.vimType;
 //Get tags assigned to VM
 var tagList = tagging.list_attached_tags(objId);
 //Loop through VM assigned tags
 for each (var tagId in tagList) {
 //get object on tag
 var theTag = tagMgr.get(tagId);
 //assign name to compare
 var tagName=theTag.name;
 //compare to our requested tag
 if (tagName == tagNameToMatch) {
 System.log("VM : " + vm.name + " has the tag : " + tagName );
 // add to array
 vmsWithSpecificTag.push(vm.name);
 }
 
 }
 }


return vmsWithSpecificTag;

2 Replies to “vRO Action to return virtual machines with a specific tag”

  1. I am having an issue with implementing this either as an action or part of a script within a workflow. At line 25 “var tagList = tagging.list_attached_tags(objId);” I am getting an error: “com.vmware.vapi.std.errors.unauthorized => {data=, messages=[]}”. I have validated the VAPI metamodel and endpoints. Other tagging operations function correctly. Has there been a change in the list_attached_tags method with regards to the parameter?

  2. Please disregard my previous comment. My script needed to be modified to handle multiple vCenters with ELM as well as handling VMs that have no tags. This post was extremely helpful. Thank you very much.

    I tried to get to your session at VMworld 2019, but I had a conflict. It would have been great to have thanked you in person. If you are interested in the details of what I worked on, please don’t hesitate to contact me.

Leave a Reply to Robert Lyons Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.