mkvm/main.go
2024-12-02 20:23:28 -08:00

84 lines
2.2 KiB
Go

package main
import (
"fmt"
"math/rand"
"sync"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"mkvm/libvirtx"
)
var (
wg sync.WaitGroup
rootCmd = cobra.Command{
Use: "mkvm name [name [name]]",
Short: "create virtual machine(s) via libvirt",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
logrus.SetLevel(logrus.DebugLevel)
conn, err := libvirtx.New()
if err != nil {
logrus.WithError(err).Fatal("error connecting to libvirt")
return
}
defer conn.Close()
network, err := getNetwork(conn)
if err != nil {
logrus.WithError(err).Fatal("error finding requested network")
}
serverBindIP := network.IPs[0].Address
port := rand.Intn(65535-1025) + 1025
serverBind := fmt.Sprintf("%s:%d", serverBindIP, port)
go runHTTPServer(serverBind)
for i, name := range args {
metadataURL := fmt.Sprintf("http://%s/%d", serverBind, i)
if err := buildCloudConfig(i, name, metadataURL); err != nil {
logrus.WithError(err).WithField("vm", name).Error("error building cloudconfig for vm")
continue
}
wg.Add(1)
if err := mkvm(conn, metadataURL, name); err != nil {
logrus.WithError(err).Error("unexpected error building VM")
wg.Done()
}
}
logrus.Info("waiting for VM(s) to finish provisioning")
wg.Wait()
},
}
argMemoryMB int
argCPUs int
argImage string
argDiskSizeGB int
// cloudinit args
argSSHKeys []string
argPackages []string
)
func main() {
if err := rootCmd.Execute(); err != nil {
panic(err)
}
}
func init() {
rootCmd.Flags().IntVarP(&argMemoryMB, "memory", "m", 1024, "amount of memory (in MB) to assign to the VM")
rootCmd.Flags().IntVarP(&argCPUs, "cpu", "c", 2, "the number of vCPU cores to assign to the VM")
rootCmd.Flags().StringVarP(&argImage, "image", "", "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2", "URL of the image to download")
rootCmd.Flags().IntVarP(&argDiskSizeGB, "disk", "d", 25, "disk size (in GB)")
rootCmd.Flags().StringArrayVarP(&argSSHKeys, "ssh-keys", "s", nil, "SSH key(s) authorzed to access the VM")
rootCmd.Flags().StringArrayVarP(&argPackages, "packages", "p", nil, "packages to install on the VM")
}