Show Table of Contents
2.13. 示例:使用 Python 创建虚拟机
创建虚拟机需要几个步骤。这里介绍的第一步将创建虚拟机本身的对象。
例 2.12. 使用 Python 创建虚拟机
这个 Python 示例创建了一个名为
在使用
vm1 的虚拟机。这个虚拟机会满足以下条件:
- 最少有 512MB 内存(以字节表示)。
vm_memory = 512 * 1024 * 1024
- 必须附加到
Default集群(因此也被附加到Default数据中心)。vm_cluster = api.clusters.get(name="Default")
- 必须基于默认的
Blank模板。vm_template = api.templates.get(name="Blank")
- 必须从虚拟硬盘引导。
vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])
vms 集合的 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_name = "vm1"
vm_memory = 512 * 1024 * 1024
vm_cluster = api.clusters.get(name="Default")
vm_template = api.templates.get(name="Blank")
vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])
vm_params = params.VM(name=vm_name,
memory=vm_memory,
cluster=vm_cluster,
template=vm_template,
os=vm_os)
try:
api.vms.add(vm=vm_params)
print "Virtual machine '%s' added." % vm_name
except Exception as ex:
print "Adding virtual machine '%s' failed: %s" % (vm_name, ex)
api.disconnect()
except Exception as ex:
print "Unexpected error: %s" % ex
如果
add 请求成功,脚本会输出以下信息:
Virtual machine 'vm1' added.

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.