Grettings!
As you already know, it is possible to define custom attributes for a virtual machine from the vm's summary tab. It is also possible to define global attibutes to all inventory vms...
Is there any chances of getting/setting these "attributes" from perl SDK?
Thanks in advance!
Certainly! The only trick is having to enumerate the Custom Fields from the CustomFieldsManager to get the key property you need to call SetField on.
Here's some working code you can start with.
#!/usr/bin/perl use strict; use warnings; use VMware::VIRuntime; my %opts = ( vmname => { type => "=s", variable => "vmname", help => "Virtual Machine Name", required => 1, }, fieldname => { type => "=s", variable => "fieldname", help => "Custom Field Name", required => 1, }, fieldvalue => { type => "=s", variable => "fieldvalue", help => "CustomFieldValue", required => 1, }, ); Opts::add_options(%opts); Opts::parse(); Opts::validate(); Util::connect(); my $vm_name = Opts::get_option("vmname"); my $field_name = Opts::get_option("fieldname"); my $field_value = Opts::get_option("fieldvalue"); my $vm_view = Vim::find_entity_view(view_type => "VirtualMachine", filter => { 'name' => $vm_name}); unless ($vm_view) { Util::disconnect(); die "Failed to find VM by name: $vm_name\n"; } my $CustomFieldsManager = Vim::get_view( mo_ref => Vim::get_service_content()->customFieldsManager ); my $field_key = FindCustomFieldKey($CustomFieldsManager, $field_name); unless ($field_key) { my $new_custom_field = CreateVMFieldDefinition($CustomFieldsManager, $field_name); $field_key = $new_custom_field->key; } SetVMFieldValue($CustomFieldsManager, $vm_view, $field_key, $field_value); sub FindCustomFieldKey { my ($cfm, $field_name) = @_; my ($field_key, @custom_fields); if ($cfm->field) { @custom_fields = @{$cfm->field}; } else { # No custom fields defined, return undef return undef; } foreach my $field ( @custom_fields ) { if ($field->name eq $field_name) { $field_key = $field->key; last; } } # will be undef if no matching field to $field_name is found return $field_key; } sub CreateVMFieldDefinition { my ($cfm, $field_name) = @_; print "Adding Custom Field \'$field_name\'...\n"; my $new_cf = $cfm->AddCustomFieldDef( name => $field_name, moType => "VirtualMachine", fieldDefPolicy => undef, fieldPolicy => undef); return $new_cf; } sub SetVMFieldValue { my ($cfm, $entity, $field_key, $field_value) = @_; print "Setting Custom Field for Virtual Machine...\n"; $cfm->SetField( entity => $entity, key => $field_key, value => $field_value ); return; }
AWESOME ! ! ! :smileygrin:
Thank you so much stumpr!!