Go.NPP-Prepper/pkg/hypervisor/virtualmachine.go

112 lines
2.9 KiB
Go
Raw Normal View History

2022-12-22 12:07:21 +00:00
package hypervisor
import (
"context"
"fmt"
"log"
2022-12-22 12:07:21 +00:00
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
2022-12-22 12:07:21 +00:00
"github.com/vmware/govmomi/vim25/types"
)
type vAPPProperty struct {
Key string
Value string
}
func SetVirtualMachineProperties(ctx context.Context, clt *vim25.Client, datacenter, virtualmachine, network string) error {
finder := find.NewFinder(clt, true)
dc, err := finder.Datacenter(ctx, datacenter)
if err != nil {
log.Fatalf("[ERROR] Unable to determine datacenter: %s", err)
}
finder.SetDatacenter(dc)
vm, err := finder.VirtualMachine(ctx, virtualmachine)
2022-12-22 12:07:21 +00:00
if err != nil {
log.Fatalf("[ERROR] Unable to determine virtual machine: %s", err)
2022-12-22 12:07:21 +00:00
}
var moref mo.VirtualMachine
vm.Properties(ctx, vm.Reference(), []string{"config.vAppConfig"}, &moref)
vappconfig := &types.VmConfigSpec{
OvfEnvironmentTransport: []string{"com.vmware.guestInfo"},
}
currentvappproperties := moref.Config.VAppConfig.GetVmConfigInfo().Property
for _, vappproperty := range currentvappproperties {
vappconfig.Property = append(vappconfig.Property, types.VAppPropertySpec{
ArrayUpdateSpec: types.ArrayUpdateSpec{
Operation: types.ArrayUpdateOperationAdd,
},
Info: &types.VAppPropertyInfo{
Key: vappproperty.Key,
ClassId: vappproperty.ClassId,
InstanceId: vappproperty.InstanceId,
Id: vappproperty.Id,
Category: vappproperty.Category,
Label: vappproperty.Label,
Type: vappproperty.Type,
TypeReference: vappproperty.TypeReference,
UserConfigurable: vappproperty.UserConfigurable,
DefaultValue: vappproperty.DefaultValue,
Value: vappproperty.Value,
Description: vappproperty.Description,
},
})
}
newvappproperties := []vAPPProperty{
2022-12-22 12:07:21 +00:00
{
Key: "guestinfo.dns.domains",
Value: "${searchPath:%s}",
2022-12-22 12:07:21 +00:00
},
{
Key: "guestinfo.dns.servers",
Value: "${dns:%s}",
},
{
Key: "guestinfo.interface.0.ip.0.address",
Value: "${autoIp:%s}",
},
{
Key: "guestinfo.interface.0.ip.0.netmask",
Value: "${netmask:%s}",
},
{
Key: "guestinfo.interface.0.route.0.gateway",
Value: "${gateway:%s}",
2022-12-22 12:07:21 +00:00
},
}
for i, vappproperty := range newvappproperties {
2022-12-22 12:07:21 +00:00
vappconfig.Property = append(vappconfig.Property, types.VAppPropertySpec{
ArrayUpdateSpec: types.ArrayUpdateSpec{
Operation: types.ArrayUpdateOperationAdd,
},
Info: &types.VAppPropertyInfo{
Key: int32(i + len(currentvappproperties)),
2022-12-22 12:07:21 +00:00
Id: vappproperty.Key,
DefaultValue: fmt.Sprintf(vappproperty.Value, network),
2022-12-22 12:07:21 +00:00
Type: "expression",
},
})
}
task, err := vm.Reconfigure(ctx, types.VirtualMachineConfigSpec{
VAppConfig: vappconfig,
})
if err != nil {
return err
}
if err := task.Wait(ctx); err != nil {
return err
}
return nil
}