Ниже приведен класс тегов, который я определил.Ключ пользовательских атрибутов является глобальным для всех ресурсов VMware и изменяет только значение для каждого ресурса.Таким образом, если вы добавляете новый ключ настраиваемого атрибута к виртуальной машине или хосту, вам необходимо добавить ключ глобально, а затем изменить значение этого ключа для этого очень конкретного ресурса.
Ниже приведен рабочий пример Java.
public class Tag{
String key;
String value;
}
public void addTags(ServiceInstance serviceInstance, VirtualMachine virtualMachine, List<Tag> tags) throws CloudServiceException, CloudParameterException{
if(EmptyUtil.isNotEmpty(tags)){
CustomFieldsManager customFieldsManager = serviceInstance.getCustomFieldsManager();
CloudValidate.resourceNotNull(customFieldsManager, "Custom Fields cannot be set for VM as CustomFieldsManager instance could not be obtained.");
CustomFieldDef[] customFieldDefs = customFieldsManager.getField();
Set<String> existingTags = getExistingTags(customFieldDefs);
for(Tag tag : tags){
if(!existingTags.contains(tag.getKey())){
updateTagsKey(customFieldsManager, tag.getKey());
}
updateTagsValue(virtualMachine, tag);
}
}
}
private void updateTagsKey(CustomFieldsManager customFieldsManager, String key){
try {
customFieldsManager.addCustomFieldDef(key, Constants.VMWARE_CUSTOMATTRIBUTE_TYPE_VM, null, null);
}catch (DuplicateName dname){
logger.warn("Custom attribute : {} already exists.", key);
}catch(Exception exception) {
logger.warn("Failed to add custom field due to : {}.", exception.getMessage());
}
}
private void updateTagsValue(VirtualMachine virtualMachine, Tag tag){
try{
logger.info("Adding {} for Virtua Machine {}", tag.toString(), virtualMachine.getName());
virtualMachine.setCustomValue(tag.getKey(), tag.getValue());
}catch(Exception exception) {
logger.warn("Failed to set custom attribute on VM due to : {}.", exception.getMessage());
}
}
private Set<String> getExistingTags(CustomFieldDef[] customFieldDefs){
Set<String> existingTags = new HashSet<>();
if(EmptyUtil.isNotEmpty(customFieldDefs)){
for(CustomFieldDef customFieldDef : customFieldDefs){
existingTags.add(customFieldDef.getName());
}
logger.debug("Existing Custom Fields from Custom Fields Manager : {}", Arrays.toString(existingTags.toArray()));
}
return existingTags;
}