2

編集:ここで 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" では、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()
4

0 に答える 0