I'm trying to collect all VMs in a datastore from a given datacenter, passed as a command line argument. Here's a snippet:
my %allvms = ();
my $clusters = Vim::find_entity_views(
view_type => 'ClusterComputeResource',
filter => { 'name' => "$cluster_name" },
);
foreach my $cluster ( @$clusters ){
print "Cluster: " . $cluster->name . "\n";
my $datastores = Vim::get_views (mo_ref_array => $cluster->datastore);
foreach my $datastore (sort @$datastores){
my $vms = Vim::get_views (mo_ref_array => $datastore->vm);
foreach my $vm ( @$vms ){
$allvms{$vm->name} = $vm->summary->config->vmPathName; $allvms{$vm->name} = $vm->name; } } } foreach ( sort keys %allvms ){ print "$_: $allvms{$_}\n"; }
But the %allvms hash is empy. What am I doing wrong?
Thanks much!
Rob
Have you looked at the named parameter "begin_entity" ?
You could probably save some logic by getting a ManagedObject Reference to your datacenter of choice, then make your find_entity_views call:
my $virtual_machine_views = Vim::find_entity_view( view_type => "VirtualMachine", begin_entity => $datacenter_moref, }
That would probably be a little easier.
But wouldn't this give me all VMs in a datacenter? I'm only interested in VMs on a given datastore.
Sorry, didn't read that detail the first time. That's also easy.
Look at the Datastore object, particular the vm property. It'll give you an array of morefs of VMs using it. Obviously, this won't include VMs that are not in the VC inventory, for that you'd have to search the datastore for files and make some assumptions about their validity by name.
That's what I thought this section of the code was doing:
my $datastores = Vim::get_views (mo_ref_array => $cluster->datastore);
foreach my $datastore (sort @$datastores){
my $vms = Vim::get_views (mo_ref_array => $datastore->vm);
But the @$vms array appears to be empty and I'm not sure why. I know that the @$datastores array is being populated, though, so it appears to be a valid array reference.
So I wrote some code almost matching what you got (only difference was variable names). It's working for me.
Is your hash declaration in a loop so it's getting reset?
Gee, I finaliy figured out what's going on. The account I'm using didn't have enough permissions in the cluster I was querying. I ran the code against another cluster and voila!
Hahaha, I feel stupid. Thanks a lot for your help, though.
At least it was something simple. Sorry I misread your post not once, but twice.