使用 libvirt-go 库中的 CreateXML 方法可以通过镜像文件创建虚拟机。以下是一个示例代码:

package main

import (
	"fmt"
	"github.com/libvirt/libvirt-go"
)

func main() {
	conn, err := libvirt.NewConnect("qemu:///system")
	if err != nil {
		fmt.Println("Failed to connect to qemu:///system")
		return
	}
	defer conn.Close()

	xml := `<domain type='kvm'>
	  <name>testvm</name>
	  <memory unit='KiB'>1048576</memory>
	  <vcpu placement='static'>1</vcpu>
	  <os>
	    <type arch='x86_64' machine='pc-i440fx-2.9'>hvm</type>
	    <boot dev='hd'/>
	  </os>
	  <devices>
	    <disk type='file' device='disk'>
	      <driver name='qemu' type='qcow2'/>
	      <source file='/path/to/image.qcow2'/>
	      <target dev='vda' bus='virtio'/>
	      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
	    </disk>
	    <interface type='network'>
	      <mac address='52:54:00:00:00:01'/>
	      <source network='default'/>
	      <model type='virtio'/>
	      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
	    </interface>
	  </devices>
	</domain>`

	dom, err := conn.DomainCreateXML(xml, 0)
	if err != nil {
		fmt.Println("Failed to create domain")
		return
	}
	defer dom.Free()

	fmt.Println("Domain created successfully")
}

在上面的代码中,我们首先使用 libvirt.NewConnect 方法连接到 QEMU/KVM hypervisor。然后,我们定义了一个 XML 配置文件,其中包含了虚拟机的名称、内存、CPU 等配置信息,以及镜像文件的路径和网络接口的配置信息。最后,我们使用 conn.DomainCreateXML 方法创建虚拟机,并在创建完成后释放资源。

使用 libvirt-go 库通过镜像文件创建虚拟机

原文地址: https://www.cveoy.top/t/topic/fYpS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录