search for vm with datacenter info in cloud event
Some checks are pending
continuous-integration/drone/push Build is passing
CI / Lint (push) Waiting to run
CI / Test (push) Waiting to run
CI / End-to-End (push) Waiting to run
CI / Publish Docker (push) Blocked by required conditions

This commit is contained in:
2024-09-13 10:08:36 +10:00
parent 2de8cf593c
commit 03701f9566
2 changed files with 57 additions and 2 deletions

View File

@@ -10,6 +10,7 @@ import (
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/view"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
@@ -158,3 +159,49 @@ func (v *Vcenter) FindVMByID(vmID string) (*VmProperties, error) {
return nil, fmt.Errorf("VM with ID %s not found in any datacenter", vmID)
}
func (v *Vcenter) FindVMByIDWithDatacenter(vmID string, dcID string) (*VmProperties, error) {
v.Logger.Debug("searching for vm id", "vm_id", vmID, "datacenter_id", dcID)
finder := find.NewFinder(v.client.Client, true)
// Create a ManagedObjectReference for the datacenter
dcRef := types.ManagedObjectReference{
Type: "Datacenter",
Value: dcID,
}
// Convert the reference to a Datacenter object
datacenter := object.NewDatacenter(v.client.Client, dcRef)
if datacenter == nil {
return nil, fmt.Errorf("Datacenter with id %s not found", dcID)
}
// Use finder.SetDatacenter to set the datacenter
finder.SetDatacenter(datacenter)
// Create a ManagedObjectReference for the VM
vmRef := types.ManagedObjectReference{
Type: "VirtualMachine",
Value: vmID,
}
var vm mo.VirtualMachine
err := v.client.RetrieveOne(v.ctx, vmRef, []string{"config", "name"}, &vm)
if err == nil {
return &VmProperties{
Datacenter: datacenter.Name(),
Vm: vm,
}, nil
} else if _, ok := err.(*find.NotFoundError); !ok {
// If the error is not a NotFoundError, return it
//return nil, fmt.Errorf("failed to retrieve VM with ID %s in datacenter %s: %w", vmID, dc.Name(), err)
v.Logger.Debug("Couldn't find vm in datacenter", "vm_id", vmID, "datacenter_name", datacenter.Name())
} else if err != nil {
return nil, fmt.Errorf("failed to retrieve VM: %w", err)
}
return nil, fmt.Errorf("VM with ID %s not found in any datacenter", vmID)
}