Monday, April 15, 2013

How to get Managed Object Reference ID ( aka MoRef ) from vSphere

If you've already scripted vSphere infrastructure you probably already know that everything has software representation also known as Managed Object. Each Managed Object has unique identifier referenced as Managed Object ID. Sometimes this Managed Object ID is needed.

In PowerCLI you can get it via following two lines
$VM = Get-VM -Name $VMName 
$VMMoref = $VM.ExtensionData.MoRef.Value
You can also use Perl script leveraging VMware vSphere Perl SDK to get Managed Object ID for particular virtual machine or datastore. If you need MOID for another entity it's pretty easy to slightly change the script below.

Script is developed and tested on vMA (VMware management Assistant) in directory /usr/lib/vmware-vcli/apps/general and script name is getmoid.pl

Here is usage example how to get MOID of datastore called FreeNAS-iSCSI-01:
./getmoid.pl --server --username --password --dsname FreeNAS-iSCSI-01

Manage Object ID: datastore-162

Here is usage example how to get MOID of virtual machine called VMA:
./getmoid.pl --server --username --password --vmname VMA
Manage Object ID: vm-122

Any feedback or comments are welcome.



#!/usr/bin/perl -w
#
# Copyright (c) 2007 VMware, Inc.  All rights reserved.
# Copyright (c) 2013 David Pasek   All rights reserved.

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/../";

use VMware::VIRuntime;

$Util::script_version = "1.0";

my %opts = (
   'vmname' => {
      type => "=s",
      help => "The name of the virtual machine",
      required => 0,
   },
   'dsname' => {
      type => "=s",
      help => "The name of the datastore",
      required => 0,
   },
);

Opts::add_options(%opts);
Opts::parse();
Opts::validate();
Util::connect();

my $vmname = Opts::get_option ('vmname');
my $dsname = Opts::get_option ('dsname');

if ($vmname) {
  &get_moid(
    view_type=>'VirtualMachine',
    mo_name=>$vmname,
  );
}

if ($dsname) {
  &get_moid(
    view_type=>'Datastore',
    mo_name=>$dsname,
  );
}

if ( !($vmname) and !($dsname)) {
  print "Select Managed Object. Use --vmname or --dsname\n";
}

Util::disconnect();
exit;

sub get_moid {
   my %params = @_;
   my $vm_moid = 0;
   my $view_type = $params{'view_type'};
   my $mo_name = $params{'mo_name'};

   my $mo_view = Vim::find_entity_view(
                   view_type => $view_type,
                   filter => {
                     'name'=> $mo_name,
                   }
   );

   if ($mo_view) {
     my $moid = $mo_view->get_property('mo_ref')->value;
     print "Manage Object ID: $moid\n";
   } else {
     print "Manage Object doesn't exist\n";
   }
}


No comments: