92 lines
1.4 KiB
Go
92 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"esxlib/client"
|
|
)
|
|
|
|
type Config struct {
|
|
Host string
|
|
User string
|
|
Password string
|
|
}
|
|
|
|
func UnmarshalFromFile(path string, v interface{}) error {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return json.Unmarshal(data, v)
|
|
}
|
|
|
|
func main() {
|
|
config := &Config{}
|
|
|
|
err := UnmarshalFromFile("config.json", config)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
url := fmt.Sprintf("https://%s:%s@%s", config.User, config.Password, config.Host)
|
|
c, err := client.NewClient(
|
|
context.TODO(),
|
|
url,
|
|
true,
|
|
client.WithSSH(fmt.Sprintf("%s:22", config.Host), config.User, config.Password))
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
ls, err := c.VirtualMachines.List(context.TODO())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
for _, vm := range ls {
|
|
fmt.Printf("%s\n", vm.Name())
|
|
}
|
|
|
|
vm, err := c.VirtualMachines.Create(context.TODO(), "test2", 1024, 20000, []byte("#!/bin/bash"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
fmt.Printf("%+v\n", vm)
|
|
|
|
err = vm.PowerOn(context.TODO())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
for {
|
|
err = vm.Update()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
addrs := vm.GetNetworkAddressV4()
|
|
if len(addrs) == 0 {
|
|
time.Sleep(time.Second * 5)
|
|
continue
|
|
}
|
|
|
|
for _, a := range addrs {
|
|
fmt.Printf("%s\n", a)
|
|
}
|
|
break
|
|
}
|
|
|
|
fmt.Printf("Destroy the vm now\n")
|
|
err = c.VirtualMachines.Destroy(context.TODO(), "test2")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|