Golang govmomi按资源池过滤虚拟机

时间:2019-06-09 08:41:46

标签: go govmomi

我目前有一些go代码,用于使用govmomi库列出虚拟机名称和资源池。在输出中,我有某种资源池标识符,而不是实际名称。因此,我有两个问题:1.是否有一种干净,简单的方法可以按资源池的名称过滤虚拟机,如govc命令:

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

2。有没有一种方法可以在所有DC中进行搜索而无需指定名称,因为我想创建goroutine在多个vSphere中进行搜索,它们具有不同的DC名称但具有相同的池。 我的代码:

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.")
}

当前输出:

SRVAP1027 ResourcePool:resgroup-3246
SRVAP1029 ResourcePool:resgroup-3246
SRVWE086 ResourcePool:resgroup-544
SRVDB087 ResourcePool:resgroup-3246
SRVAP1031 ResourcePool:resgroup-49
SRVAP1036 ResourcePool:resgroup-49

0 个答案:

没有答案