封装govmomi操作vsphere

brownchen · · 1150 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

最近由于公司需求,需要云管平台操作vsphere,大致看了govmomi源码后用golang封装了操作vsphere的常用方法:

  • TestFindAllVM 列出vsphere中所有vm名及其uuid
  • TestFindVMByUuid 根据uuid查找vm
  • TestVMPowerOff 关闭vm
  • TestVMPowerOn 开启vm
  • TestResizeVMCPU 修改vm cpu
  • TestResizeVMMem 修改vm 内存
  • TestCreateDisk vm新增磁盘
  • TestVMDestory 销毁vm
package test

import (
    "context"
    "encoding/json"
    "fmt"
    "net/url"
    "testing"

    "github.com/vmware/govmomi"
    "github.com/vmware/govmomi/object"
    "github.com/vmware/govmomi/view"
    "github.com/vmware/govmomi/vim25"
    "github.com/vmware/govmomi/vim25/mo"
    "github.com/vmware/govmomi/vim25/types"
)

const (
    ip       = ""
    user     = ""
    password = ""
)

func Conn() (*vim25.Client, error) {
    ctx := context.Background()
    u := &url.URL{
        Scheme: "https",
        Host:   ip,
        Path:   "/sdk",
    }
    u.User = url.UserPassword(user, password)
    client, err := govmomi.NewClient(ctx, u, true)
    if err != nil {
        return nil, err
    }
    return client.Client, nil
}
func GetVM() (*object.VirtualMachine, error) {
    ctx := context.Background()
    c, err := Conn()
    if err != nil {
        return nil, err
    }
    uuid := "42320b75-02a3-3e4f-6fbe-31175fef0f06"
    // uuid := "4232d9d2-d01d-1dfc-0a8a-df2f8437df16"
    searchIndex := object.NewSearchIndex(c)
    reference, err := searchIndex.FindByUuid(ctx, nil, uuid, true, nil)
    if reference == nil {
        return nil, err
    }
    vm := object.NewVirtualMachine(c, reference.Reference())
    return vm, nil
}

func TestConn(t *testing.T) {

    u := &url.URL{
        Scheme: "https",
        Host:   ip,
        Path:   "/sdk",
    }
    ctx := context.Background()
    u.User = url.UserPassword(user, password)
    client, err := govmomi.NewClient(ctx, u, true)
    if err != nil {
        panic(err)
    }
    fmt.Println(client)
}

func TestFindAllVM(t *testing.T) {
    ctx := context.Background()
    c, err := Conn()
    if err != nil {
        panic(err)
    }
    m := view.NewManager(c)
    v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)
    if err != nil {
        panic(err)
    }
    defer v.Destroy(ctx)
    var vms []mo.VirtualMachine
    err = v.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary"}, &vms)
    if err != nil {
        panic(err)
    }
    for _, vm := range vms {
        fmt.Printf("Name:%s, UUID:%s\n", vm.Summary.Config.Name, vm.Summary.Config.Uuid)
    }
}

func TestFindVMByUuid(t *testing.T) {
    ctx := context.Background()
    c, err := Conn()
    if err != nil {
        panic(err)
    }
    // uuid := "42322ae0-6dd5-fe3a-539e-6603aeab80d4"
    uuid := "4232d9d2-d01d-1dfc-0a8a-df2f8437df16"
    searchIndex := object.NewSearchIndex(c)
    reference, err := searchIndex.FindByUuid(ctx, nil, uuid, true, nil)
    if reference == nil {
        panic("vm not found")
    }
    vm := object.NewVirtualMachine(c, reference.Reference())
    fmt.Println(vm)
}

func TestVMPowerOff(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    task, err := vm.PowerOff(ctx)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("vm is poweroff.")
}

func TestVMPowerOn(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    task, err := vm.PowerOn(ctx)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("vm is poweron.")
}

func TestResizeVMCPU(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    config := types.VirtualMachineConfigSpec{
        NumCPUs: 2,
    }
    task, err := vm.Reconfigure(ctx, config)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("resize cpu ok")
}

func TestResizeVMMem(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    config := types.VirtualMachineConfigSpec{
        MemoryMB: 2 * 1024,
    }
    task, err := vm.Reconfigure(ctx, config)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("resize mem ok")
}

func NewBool(v bool) *bool {
    return &v
}
func NewInt32(v int32) *int32 {
    return &v
}
func TestCreateDisk(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    spec := types.VirtualMachineConfigSpec{}
    config := &types.VirtualDeviceConfigSpec{
        Operation:     types.VirtualDeviceConfigSpecOperationAdd,
        FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,
        Device: &types.VirtualDisk{
            VirtualDevice: types.VirtualDevice{
                Key:           2002,
                ControllerKey: 1000,
                UnitNumber:    NewInt32(3), // zero default value
                Backing: &types.VirtualDiskFlatVer2BackingInfo{
                    DiskMode:        string(types.VirtualDiskModePersistent),
                    ThinProvisioned: NewBool(false),
                    VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{
                        FileName: "[datastore1]",
                    },
                },
            },
            CapacityInKB: 30 * 1024 * 1024,
        },
    }
    spec.DeviceChange = append(spec.DeviceChange, config)
    task, err := vm.Reconfigure(ctx, spec)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
}

func TestVMDestory(t *testing.T) {
    ctx := context.Background()
    vm, err := GetVM()
    if err != nil {
        panic(err)
    }
    task, err := vm.Destroy(ctx)
    if err != nil {
        panic(err)
    }
    err = task.Wait(ctx)
    if err != nil {
        panic(err)
    }
    fmt.Println("vm is destory.")
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:brownchen

查看原文:封装govmomi操作vsphere

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1150 次点击  
加入收藏 微博
1 回复  |  直到 2021-05-18 16:20:34
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传