some vm properties are populated
This commit is contained in:
@@ -9,9 +9,11 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/vmware/govmomi"
|
||||
"github.com/vmware/govmomi/find"
|
||||
"github.com/vmware/govmomi/view"
|
||||
"github.com/vmware/govmomi/vim25/mo"
|
||||
"github.com/vmware/govmomi/vim25/soap"
|
||||
"github.com/vmware/govmomi/vim25/types"
|
||||
)
|
||||
|
||||
type Vcenter struct {
|
||||
@@ -20,6 +22,11 @@ type Vcenter struct {
|
||||
client *govmomi.Client
|
||||
}
|
||||
|
||||
type VmProperties struct {
|
||||
Vm mo.VirtualMachine
|
||||
Datacenter string
|
||||
}
|
||||
|
||||
// New creates a new Vcenter with the given logger
|
||||
func New(logger *slog.Logger) *Vcenter {
|
||||
|
||||
@@ -104,3 +111,44 @@ func (v *Vcenter) FindVMByName(vmName string) ([]mo.VirtualMachine, error) {
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (v *Vcenter) FindVMByID(vmID string) (*VmProperties, error) {
|
||||
finder := find.NewFinder(v.client.Client, true)
|
||||
|
||||
// List all datacenters
|
||||
datacenters, err := finder.DatacenterList(v.ctx, "*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list datacenters: %w", err)
|
||||
}
|
||||
|
||||
for _, dc := range datacenters {
|
||||
// Set the current datacenter
|
||||
finder.SetDatacenter(dc)
|
||||
|
||||
// Create a ManagedObjectReference for the VM
|
||||
vmRef := types.ManagedObjectReference{
|
||||
Type: "VirtualMachine",
|
||||
Value: vmID,
|
||||
}
|
||||
|
||||
// Try to find the VM by ID in the current datacenter
|
||||
//vm, err := finder.ObjectReference(v.ctx, vmRef)
|
||||
|
||||
var vm mo.VirtualMachine
|
||||
err := v.client.RetrieveOne(v.ctx, vmRef, []string{"config", "name"}, &vm)
|
||||
if err != nil {
|
||||
// If the error is not a NotFoundError, return it
|
||||
if err == err.(*find.NotFoundError) {
|
||||
return nil, fmt.Errorf("failed to retrieve VM with ID %s in datacenter %s: %w", vmID, dc.Name(), err)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to retrieve VM: %w", err)
|
||||
}
|
||||
|
||||
return &VmProperties{
|
||||
Datacenter: dc.Name(),
|
||||
Vm: vm,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("VM with ID %s not found in any datacenter", vmID)
|
||||
}
|
||||
|
Reference in New Issue
Block a user