Question

I would like to see some info for all the virtualmachines in my vcenter, right now I have:

require 'rbvmomi'

vim1 = RbVmomi::VIM.connect host: 'vcenter.foo.tld', ssl: true, insecure: true, user: 'keith', password: 'NSABACKDOOR' 
dc1 = vim1.serviceInstance.find_datacenter("Datacenter Name") or fail "datacenter not found"

def list_vms(dc,vim)
  dc.vmFolder.children.each do |vm| 
    if vm.is_a? RbVmomi::VIM::VirtualMachine
      puts vm.name
    end
  end
end

list_vms(dc1,vim1)

But that only returns the hosts (i.e. puts hostnames) in one datacenter, and only those that are in the top level in the folder-hierarchy. I need them all, no matter where.

Was it helpful?

Solution

Almost there - I had exactly the same issue - your loop is skipping subfolders. To get all of the VMs, you need to recurse down thru them. Try something like this (ripped from my own working code):

def vms(folder) # recursively go thru a folder, dumping vm info
   folder.childEntity.each do |x|
      name, junk = x.to_s.split('(')
      case name
      when "Folder"
         vms(x)
      when "VirtualMachine"
         puts x.name
      else
         puts "# Unrecognized Entity " + x.to_s
      end
   end
end

That's obviously starting at the top-level folder in a datacenter, not the DC itself. I don't actually have multiple datacenters in my setup - but it doesn't appear that find_datacenter supports something like .each - so you'd probably want to wrap that up in a loop like:

 dcs = ['firstdc', 'seconddc', 'thirddc']
 dcs.each do |dc|
    vms(vim1.serviceInstance.find_datacenter(dc).vmFolder)
 end

OTHER TIPS

You can also do this without manual recursion by (ab?)using the CreateContainerView function:

vim.serviceContent.viewManager.CreateContainerView({
  container: dc.vmFolder,
  type:      ['VirtualMachine'],
  recursive: true
}).view

I've used dc.vmFolder as the root, as that's what was given in the question, but you can also swap in vim.rootFolder to get a list of the VMs in all DCs.

It will not however recurse through all childitems of children and their sisters. I wrote something similar using pyvmomi that visits each node of the tree of objects.

pseudo like this: stack being the most top level node list

def TreeSpider(stack)
    while stack

        for node in stack:
            remove node from stack
            do custom-stuff

            if node (has child):
                stack.append(child) #or a for loop for each child

also check out tree traversal in general

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top