1

I currently have some go code to list VM names and Resource Pools with govmomi library. In the output I have some sort of Resource Pool identifiers, not actual names. So I have two questions: 1. Is there a clean and simple way to filter VMs by Resource Pool's name, as govc command:

govc find . -type m -resourcePool $(govc find -i . -name PoolName) 

2. Is there a way to search in all DCs, without specifying names, as I want to create goroutine to search in a number of vSpheres, they have different DC names but same Pools. My code:

package main

import (
    "flag"
    "fmt"
    "net/url"
    "os"
    "sync"
    "github.com/vmware/govmomi"
    "github.com/vmware/govmomi/find"
    "github.com/vmware/govmomi/property"
    "github.com/vmware/govmomi/vim25/mo"
    "github.com/vmware/govmomi/vim25/types"
    "golang.org/x/net/context"
)

var vsphereUrl = "https://name:pass@vsphere/sdk"
var insecureFlag = false


func exit(err error) {
    fmt.Fprintf(os.Stderr, "Error: %s\n", err)
    os.Exit(1)
}


func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    flag.Parse()
    u, err := url.Parse(vsphereUrl)
    if err != nil {
        exit(err)
    }
    c, err := govmomi.NewClient(ctx, u, insecureFlag)
    if err != nil {
        exit(err)
    }
    f := find.NewFinder(c.Client, true)
    dcs := []string{"First-DC", "Second-DC"}
    var group sync.WaitGroup
    for _, dc := range dcs {
        group.Add(1)
        go func(ctx context.Context, dc string, f *find.Finder, c *govmomi.Client, group *sync.WaitGroup) {
            defer group.Done()
            dcObj, err := f.DatacenterOrDefault(ctx, dc)
            if err != nil {
                exit(err)
            }
            f.SetDatacenter(dcObj)
            vms, err := f.VirtualMachineList(ctx, "*")
            if err != nil {
                exit(err)
            }
            pc := property.DefaultCollector(c.Client)
            var refs []types.ManagedObjectReference
            for _, vm := range vms {
                refs = append(refs, vm.Reference())
            }
            var vmt []mo.VirtualMachine
            err = pc.Retrieve(ctx, refs, []string{"name", "resourcePool"}, &vmt)
            if err != nil {
                exit(err)
            }
            for _, vm := range vmt {
                fmt.Println(vm.Name, vm.ResourcePool)
            }
        }(ctx, dc, f, c, &group)
    }
    group.Wait()
    fmt.Println("Done.")
}

Current output:

SRVAP1027 ResourcePool:resgroup-3246
SRVAP1029 ResourcePool:resgroup-3246
SRVWE086 ResourcePool:resgroup-544
SRVDB087 ResourcePool:resgroup-3246
SRVAP1031 ResourcePool:resgroup-49
SRVAP1036 ResourcePool:resgroup-49
Alex Nikitin
  • 514
  • 5
  • 12
  • Do you mean, rather than `dcs := []string{"First-DC", "Second-DC"}`, you don't want to hard-code them, you want to dynamically find them? – jnovack Jul 06 '20 at 17:47

0 Answers0