как создать вмс с пывмоми - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь создать программу python, которая создаст указанное количество идентичных виртуальных машин. Я использовал примеры сценариев сообщества, чтобы получить как можно больше работы, но сейчас я полностью застрял.

#!/usr/bin/env python


"""
vSphere SDK for Python program for creating tiny VMs (1vCPU/128MB)
"""

import atexit
import hashlib
import json

import random
import time

import requests
from pyVim import connect
from pyVmomi import vim

from tools import cli
from tools import tasks

from add_nic_to_vm import add_nic, get_obj



def get_args():
    """
    Use the tools.cli methods and then add a few more arguments.
    """
    parser = cli.build_arg_parser()

    parser.add_argument('-c', '--count',
                        type=int,
                        required=True,
                        action='store',
                        help='Number of VMs to create')

    parser.add_argument('-d', '--datastore',
                        required=True,
                        action='store',
                        help='Name of Datastore to create VM in')

    parser.add_argument('--datacenter',
                        required=True,
                        help='Name of the datacenter to create VM in.')

    parser.add_argument('--folder',
                        required=True,
                        help='Name of the vm folder to create VM in.')

    parser.add_argument('--resource-pool',
                        required=True,
                        help='Name of resource pool to create VM in.')

    parser.add_argument('--opaque-network',
                        help='Name of the opaque network to add to the new VM')

    # NOTE (hartsock): as a matter of good security practice, never ever
    # save a credential of any kind in the source code of a file. As a
    # matter of policy we want to show people good programming practice in
    # these samples so that we don't encourage security audit problems for
    # people in the future.

    args = parser.parse_args()

    return cli.prompt_for_password(args)



def create_dummy_vm(vm_name, service_instance, vm_folder, resource_pool,
                    datastore):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=128, numCPUs=1,
                               files=vmx_file, guestId='dosGuest',
                               version='vmx-07')

    print("Creating VM {}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])

A=1
def main():
    """
    Simple command-line program for creating Dummy VM based on Marvel character
    names
    """
    name = "computer" + str(A)

    args = get_args()



    service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                     user=args.user,
                                                     pwd=args.password,
                                                     port=int(args.port))
    if not service_instance:
        print("Could not connect to the specified host using specified "
              "username and password")
        return -1

    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.RetrieveContent()
    datacenter = get_obj(content, [vim.Datacenter], args.datacenter)
    vmfolder = get_obj(content, [vim.Folder], args.folder)
    resource_pool = get_obj(content, [vim.ResourcePool], args.resource_pool)



    vm_name =  name
    create_dummy_vm(vm_name, service_instance, vmfolder, resource_pool,
                        args.datastore)
    A + 1
    if args.opaque_network:
            vm = get_obj(content, [vim.VirtualMachine], vm_name)
            add_nic(service_instance, vm, args.opaque_network)
    return 0


# Start program
if __name__ == "__main__":
    main()

Ошибка, которую я получаю при запуске:

   Creating VM computer1...
Traceback (most recent call last):
  File "create_vm.py", line 142, in <module>
    main()
  File "create_vm.py", line 133, in main
    args.datastore)
  File "create_vm.py", line 98, in create_dummy_vm
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
AttributeError: 'NoneType' object has no attribute 'CreateVM_Task'

Я знаю, что мой CreateVM_task возвращает параметр none, но я не могу понять, почему.

1 Ответ

0 голосов
/ 11 марта 2020

Проблема была с параметрами конфигурации. С текущим кодом объекты datacenter и vmfolder возвращаются как ноль при печати. Чтобы исправить это, я отредактировал его в следующем блоке.

content = service_instance.RetrieveContent()
datacenter = content.rootFolder.childEntity[0]
vmfolder = datacenter.vmFolder
hosts = datacenter.hostFolder.childEntity
resource_pool = hosts[0].resourcePool
...