Skip to content

Instantly share code, notes, and snippets.

@sky-joker
Last active May 28, 2017 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sky-joker/9a1b7025da57602cbfb8377a8f684ddd to your computer and use it in GitHub Desktop.
Save sky-joker/9a1b7025da57602cbfb8377a8f684ddd to your computer and use it in GitHub Desktop.
govmomiで仮想インスタンス情報を取得
package main
import (
"context"
"fmt"
"net/url"
"os"
"text/tabwriter"
"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"
)
const (
URL = "https://vCenterIP/sdk" // ESXi or vCenter URL
UserName = "administrator@vsphere.local" // ログインユーザー
Password = "password" // ログインパスワード
Insecure = true // 自己証明書の許可 `true`
)
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()
// 接続先のURLをパース
u, err := url.Parse(URL)
if err != nil {
exit(err)
}
// ログインユーザーとパスワードをセット
u.User = url.UserPassword(UserName, Password)
// ログイン
c, err := govmomi.NewClient(ctx, u, Insecure)
if err != nil {
exit(err)
}
f := find.NewFinder(c.Client, true)
// データセンターを検索
dc, err := f.DefaultDatacenter(ctx)
if err != nil {
exit(err)
}
// 見つけたデータセンターのローカルコールを使う
f.SetDatacenter(dc)
// データセンター内の仮装インスタンスリストを取得
vms, err := f.VirtualMachineList(ctx, "*")
if err != nil {
exit(err)
}
// 参照リストに変換する
var refs []types.ManagedObjectReference
for _, vm := range vms {
refs = append(refs, vm.Reference())
}
// 指定したプロパティの取得
pc := property.DefaultCollector(c.Client)
var vmt []mo.VirtualMachine
err = pc.Retrieve(ctx, refs, []string{"config"}, &vmt) // ここでは `config` プロパティを指定
if err != nil {
exit(err)
}
// 仮想インスタンス情報を出力
tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
fmt.Fprintf(tw, "Name:\tCPU:\tMemory(MB):\tGuest:\n")
for _, vm := range vmt {
fmt.Fprintf(tw, "%s\t", vm.Config.Name)
fmt.Fprintf(tw, "%d\t", vm.Config.Hardware.NumCPU)
fmt.Fprintf(tw, "%d\t", vm.Config.Hardware.MemoryMB)
fmt.Fprintf(tw, "%s\t", vm.Config.GuestFullName)
fmt.Fprintf(tw, "\n")
}
tw.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment