github.com/vmware/govmomi@v0.51.0/examples/virtualmachines/main.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  /*
     6  This example program shows how the `view` package can
     7  be used to navigate a vSphere inventory structure using govmomi.
     8  */
     9  
    10  package main
    11  
    12  import (
    13  	"context"
    14  	"fmt"
    15  
    16  	"github.com/vmware/govmomi/examples"
    17  	"github.com/vmware/govmomi/view"
    18  	"github.com/vmware/govmomi/vim25"
    19  	"github.com/vmware/govmomi/vim25/mo"
    20  )
    21  
    22  func main() {
    23  	examples.Run(func(ctx context.Context, c *vim25.Client) error {
    24  		// Create view of VirtualMachine objects
    25  		m := view.NewManager(c)
    26  
    27  		v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"VirtualMachine"}, true)
    28  		if err != nil {
    29  			return err
    30  		}
    31  
    32  		defer v.Destroy(ctx)
    33  
    34  		// Retrieve summary property for all machines
    35  		// Reference: https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vim.VirtualMachine.html
    36  		var vms []mo.VirtualMachine
    37  		err = v.Retrieve(ctx, []string{"VirtualMachine"}, []string{"summary"}, &vms)
    38  		if err != nil {
    39  			return err
    40  		}
    41  
    42  		// Print summary per vm (see also: govc/vm/info.go)
    43  
    44  		for _, vm := range vms {
    45  			fmt.Printf("%s: %s\n", vm.Summary.Config.Name, vm.Summary.Config.GuestFullName)
    46  		}
    47  
    48  		return nil
    49  	})
    50  }