Search code examples
javaapisdkvmwarevsphere

VI JAVA: Getting Custom Fields (Names and Values) from Virtual Machines


The Custom Fields of my Virtual Machines (Name and Value). Those fields that are located under "annotations" on the Summary tab. Nope, I don't need the annotation property itself, I really do need the Custom Fields.

I've managed to the the values themselves from the custom fields by doing vm.getSummary.getCustomValue, then casting it to CustomFieldStringValue and doing .getValue for each Custom Field of the array.

Here's an example, (vmObject is the object I created for the fields that I need to grab):

CustomFieldValue[] customFieldValue = vm.getSummary().getCustomValue();       
CustomFieldStringValue BU = (CustomFieldStringValue) customFieldValue[0];
vmObject.setBusinessUnit(BU.getValue());

I know there's CustomFieldsManager and CustomFieldDef, they both have the "name" property that I need, what I don't know is how do I map to these from where's I'm currently at...

Edit/Progress: So I've managed to grab CustomFieldsManager and CustomFieldsDef, by doing:

ManagedObjectReference customFieldOR = si.getServiceContent().getCustomFieldsManager();
        CustomFieldsManager CFManager = new CustomFieldsManager(vm.getServerConnection(), customFieldOR);
        CustomFieldDef[] CFDef = CFManager.getField();

The bad thing about this is that I would need to iterate through the CustomFieldDef array for every VM and Custom Field in the VM... cringe


Solution

  • Well, it looks like iterating is the way to go. I guess the upside is that a vsphere call is not done on each iteration, since I managed to grab all custom fields on one or two calls:

    ManagedObjectReference customFieldOR = si.getServiceContent().getCustomFieldsManager();
            CustomFieldsManager CFManager = new CustomFieldsManager(vm.getServerConnection(), customFieldOR);
            CustomFieldDef[] CFDef = CFManager.getField();
    

    There, I have an array of all custom fields.

    Then, when iterating through VMs, I grabbed their CustomFieldValue property, which has the Key. From there on, its mapping Keys using the CustomFieldDef and CustomFieldValue Arrays. Keeping in mind that CustomFieldStringValue is the property that has the actual Value of the Custom Field - so casting from CustomFieldValue to CustomFieldStringValue is needed.

    Suggested improvements are always welcome! Hope this helps folks in the future.