Show Table of Contents
2.15. 示例:使用 Python 创建虚拟机存储磁盘
要使新创建的虚拟机可以访问具有持久性的存储,您需要创建并附加一个磁盘。
例 2.14. 使用 Python 创建虚拟机存储磁盘
这个 Python 示例创建一个 8GB
在使用
virtio 磁盘,并把它附加到名为 vm1 的虚拟机上。这个磁盘满足以下条件:
- 必须存储在名为
data1的存储域中,disk_storage_domain = params.StorageDomains(storage_domain=[api.storagedomains.get(name="data1")])
- 磁盘的容量是 8GB,
disk_size = 8*1024*1024
- 必须是一个
system类磁盘(和data相对应),disk_type = "system"
- 必须是
virtio存储设备,disk_interface = "virtio"
- 以
cow格式保存,disk_format = "cow"
- 必须被标记为一个可用的引导设备。
disk_bootable = True
disks 集合的 add 方法创建磁盘前,把这些选项组合在一起作为磁盘参数项。
from ovirtsdk.api import API
from ovirtsdk.xml import params
try:
api = API (url="https://HOST",
username="USER@DOMAIN",
password="PASS",
ca_file="ca.crt")
vm = api.vms.get(name="vm1")
sd = params.StorageDomains(storage_domain=[api.storagedomains.get(name="data1")])
disk_size = 8*1024*1024
disk_type = "system"
disk_interface = "virtio"
disk_format = "cow"
disk_bootable = True
disk_params = params.Disk(storage_domains=sd,
size=disk_size,
type_=disk_type,
interface=disk_interface,
format=disk_format,
bootable=disk_bootable)
try:
d = vm.disks.add(disk_params)
print "Disk '%s' added to '%s'." % (d.get_name(), vm.get_name())
except Exception as ex:
print "Adding disk to '%s' failed: %s" % (vm.get_name(), ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
如果
add 请求成功,脚本会输出以下信息:
Disk 'vm1_Disk1' added to 'vm1'.

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.