编辑:在这里交叉发布到 r/vmware 中的 reddit
我是使用 VMWare API 的新手,特别是尝试使用 pyVmomi。我很难理解这一切是如何结合在一起的。我想要完成的只是: 1. 获取数据存储上的 vmx/vmdk 并将其添加到清单(RegisterVM_Task ?) 2. 进入清单后,转换为模板如果上述 2 可以组合成1个过程,更好。基本上到目前为止,我所能做的就是连接到我的 vcenter 端点并通过 pyVmomi 获得有效连接。这是我拥有的相关代码,并且一直在尝试使用但没有成功:
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import requests
import ssl
#hacky way around SSL certificate checks in Python 2.7.9+
requests.packages.urllib3.disable_warnings()
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
# Create connection to vcenter
hostname = 'vcenter'
username = 'username'
passwd = 'password'
try:
si = SmartConnect(host=hostname, user=username, pwd=passwd, port=int(443))
except IOError, e:
pass
if not si:
print "Could not connect to the specified host using specified username and password"
# Do stuff
content = si.RetrieveContent()
si.content.rootFolder.RegisterVM_Task("[dvsolidfire01-vmware-general] packer_images/centos7-vmware-2015-10-13/devit-centos7-vmware-2015-10-13.vmx", "template-test", asTemplate=True)
它返回 vim.Task:task-XXXXX 的作用,然后我看到 vcenter 控制台中的实际任务失败并出现以下错误:“指定的参数不正确:主机”所以如果我尝试指定主机/集群字符串,我收到以下错误:“TypeError: For "host" expected type vim.HostSystem, but got str" OK,那么如何指定 vim.HostSystem 类型呢?我的语法/过程对于我试图尝试的内容是否正确?如果没有任何示例或文档,这很难弄清楚。任何帮助,将不胜感激!(是的,我看过 pyvmomi 样本,但在这里它们对我没有帮助)。谢谢!
我已经通过下面的代码通过 PowerCLI 实现了我所描述的内容:
# Add VMX to Inventory and convert to template
$vCenter='vcenter'
$vCenterUser='username'
$vCenterUserPassword='password'
write-host "Connecting to vCenter Server $vCenter" -foreground green
Connect-viserver $vCenter -user $vCenterUser -password $vCenterUserPassword -WarningAction 0
# Set Cluster to MyCluster
$Cluster = "MyCluster"
# Get random ESX host from Cluster list
$ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1
write-host "Adding to inventory and converting to template..." -foreground green
$VM = New-VM -VMFilePath $VMXFile -VMHost $ESXHost
$template = Get-VM $VM | Set-VM -ToTemplate -Name "Template-Test" -Confirm:$false
# Move template to Templates folder
$folder = Get-Folder -ID "Folder-group-v22506"
Move-Inventory -Item $template -Destination $folder
我真的需要从 Linux 主机上运行它,所以 pyvmomi 更可取。我不确定为什么文档或用法与 PowerCLI 相比如此复杂和不直观。任何帮助将不胜感激!
谢谢!
已解决:所以我已经弄清楚了这一点,希望我对此的尝试和挫败感会产生其他人在偶然发现时可以使用的东西。
对于任何可能需要做类似事情的人,我已尝试尽可能地记录它。代码相对简单,因为我没有使用类或实例化我自己的对象(还)。当前版本已经完成了我需要的(目前)。开始了:
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import atexit
import time
def main():
def get_uuid(vmfolder, vmname, vmstatus):
"""
Get UUID of specific orphaned vm from vmfolder ManagedObject
"""
# if this is a group it will have children, if so iterate through all the VMs in said parent
if hasattr(vmfolder, 'childEntity'):
vmlist = vmfolder.childEntity
for vm in vmlist:
summary = vm.summary
if summary.config.name == vmname and summary.runtime.connectionState == vmstatus:
return summary.config.instanceUuid
# Environment vars
hostname = 'vcenter'
username = 'username'
from getpass import getpass
passwd = getpass("enter vcenter pass: ")
#hacky workaround to ssl cert warnings in Python 2.7.9+
#http://www.errr-online.com/index.php/tag/pyvmomi/
import requests, ssl
requests.packages.urllib3.disable_warnings()
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context
# Make connection to vcenter
try:
si = SmartConnect(host=hostname, user=username, pwd=passwd, port=int(443))
except IOError, e:
pass
if not si:
print "Could not connect to the specified host using specified username and password"
atexit.register(Disconnect, si)
# Get vcenter content object
content = si.RetrieveContent()
# Get list of DCs in vCenter and set datacente to the vim.Datacenter object corresponding to the "DC01" DC
datacenters = content.rootFolder.childEntity
for dc in datacenters:
if dc.name == "DC01":
datacenter = dc
# Get List of Folders in the "DC01" DC and set tfolder to the vim.Folder object corresponding to the "Templates" folder
dcfolders = datacenter.vmFolder
vmfolders = dcfolders.childEntity
for folder in vmfolders:
if folder.name == "Templates":
tfolder = folder
# Set "Discovered virtual machine" folder to orphan_folder for future use.
elif folder.name == "Discovered virtual machine":
orphan_folder = folder
# Get vim.HostSystem object for specific ESX host to place template on
esxhost = content.searchIndex.FindByDnsName(None, "dvesx10.dev.tsi.lan", vmSearch=False)
# Clean up orphaned VM from packer build (since they don't do it for some reason)
orphan_uuid = get_uuid(orphan_folder, "devit-centos7-vmware-2015-10-15", "orphaned")
if orphan_uuid not None:
vm = content.searchIndex.FindByUuid(None, orphan_uuid, True, True)
vm.Destroy_Task()
# Wait 10 seconds until VMWare updates that the orphaned item has been deleted before trying to create a new one
time.sleep(10)
# Wow, we can actually do stuff now! Add the VMX in the specified path to the inventory as a template within the "Templates" folder
tfolder.RegisterVM_Task("[dvsolidfire01-vmware-general] packer_images/centos7-vmware-2015-10-15/devit-centos7-vmware-2015-10-15.vmx", "CentOS 7 - 2015Q4 - Test", asTemplate=True, host=esxhost)
if __name__ == "__main__":
main()