def create_library_item(self, library_id, item_name, item_description, item_type):
        """
        Create a library item in the specified library

        """
        lib_item_spec = self.get_libraryitem_spec(client_token=generate_random_uuid(),
                                                  name=item_name,
                                                  description=item_description,
                                                  library_id=library_id,
                                                  library_item_type=item_type)
        # Create a library item
        return self.client.library_item_service.create(create_spec=lib_item_spec,
                                                       client_token=generate_random_uuid())
Ejemplo n.º 2
0
    def __init__(self):
        parser = sample_cli.build_arg_parser()

        parser.add_argument('--resourcepoolname',
                            default='Compute-ResourcePool',
                            help='The name of the resource pool to be used.')

        parser.add_argument('--libitemname',
                            required=True,
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')

        args = sample_util.process_cli_args(parser.parse_args())

        self.vm_id = None
        self.vm_name = 'deployed-vm-' + str(generate_random_uuid())

        self.lib_item_name = args.libitemname
        self.resourcepoolname = args.resourcepoolname
        self.cleardata = args.cleardata

        # Connect to vAPI Endpoint on vCenter Server
        self.client = create_vsphere_client(server=args.server,
                                            username=args.username,
                                            password=args.password)
    def _execute(self):
        # Build the storage backing for the library to be created using given datastore name
        self.datastore_name = self.args.datastorename
        storage_backings = self.helper.create_storage_backings(
            service_manager=self.servicemanager,
            datastore_name=self.datastore_name)

        # Create a local content library backed by the VC datastore using vAPIs
        self.local_lib_id = self.helper.create_local_library(
            storage_backings, self.lib_name)

        # Create a new library item in the content library for uploading the files
        self.lib_item_id = self.helper.create_library_item(
            library_id=self.local_lib_id,
            item_name=self.lib_item_name,
            item_description='Sample template from ova file',
            item_type='ovf')
        print('Library item created. ID: {0}'.format(self.lib_item_id))

        ova_file_map = self.helper.get_ova_file_map(
            self.SIGNED_OVA_RELATIVE_DIR,
            local_filename=self.SIGNED_OVA_FILENAME)
        # Create a new upload session for uploading the files
        # To ignore expected warnings and skip preview info check,
        # you can set create_spec.warning_behavior during session creation
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=self.lib_item_id),
            client_token=generate_random_uuid())
        self.helper.upload_files_in_session(ova_file_map, session_id)

        # Wait for terminal preview state and obtain preview warnings if any
        self.wait_for_terminal_preview_state(session_id, AVAILABLE)
        session = self.client.upload_service.get(session_id)
        preview_info = session.preview_info

        # Collect generated preview warning types
        preview_warning_types = []
        print('Preview warnings for the session are the following:')
        for preview_warning in preview_info.warnings:
            print(preview_warning.message.default_message)
            preview_warning_types.append(preview_warning.type)

        # Ignore preview warnings on session
        ignore_warning_behaviors = []
        for warning_type in preview_warning_types:
            warning_behavior = WarningBehavior(type=warning_type, ignored=True)
            ignore_warning_behaviors.append(warning_behavior)
        self.client.upload_service.update(
            session_id,
            update_spec=UpdateSessionModel(
                warning_behavior=ignore_warning_behaviors))
        print(
            'All preview warnings are ignored, proceeding to complete the session'
        )

        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        print(
            'Uploaded ova file as an ovf template to library item {0}'.format(
                self.lib_item_id))
    def create_subscribed_library(self, pub_lib_url, sub_lib_name):
        # Build the subscription information using the publish URL of the published
        # library

        sub_info = SubscriptionInfo()
        sub_info.authentication_method = SubscriptionInfo.AuthenticationMethod.NONE
        # on_demand = False for library and item level publish
        # on_demand = True for only item level publish, the library level
        #             publish will only sync the item metadata
        sub_info.on_demand = False
        sub_info.automatic_sync_enabled = True
        sub_info.subscription_url = pub_lib_url

        # Build the specification for the subscribed library
        sub_spec = LibraryModel()
        sub_spec.name = sub_lib_name
        sub_spec.type = sub_spec.LibraryType.SUBSCRIBED
        sub_spec.subscription_info = sub_info
        sub_spec.storage_backings = self.storage_backings

        sub_lib_id = self.client.subscribed_library_service.create(
            create_spec=sub_spec, client_token=generate_random_uuid())
        self.sub_libs_to_clean.append(sub_lib_id)
        print("Subscribed library created, id: {0}".format(sub_lib_id))
        sub_lib = self.client.subscribed_library_service.get(sub_lib_id)
        return sub_lib
    def setup(self):
        parser = sample_cli.build_arg_parser()
        parser.add_argument('-n',
                            '--vm_name',
                            action='store',
                            help='Name of the testing vm')
        parser.add_argument('-clustername',
                            '--clustername',
                            help='The name of the cluster to be used.')
        parser.add_argument('-libitemname',
                            '--libitemname',
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')
        args = sample_util.process_cli_args(parser.parse_args())
        self.lib_item_name = args.libitemname
        self.cluster_name = args.clustername
        self.vm_name = args.vm_name

        self.servicemanager = ServiceManager(args.server, args.username,
                                             args.password,
                                             args.skipverification)
        self.servicemanager.connect()
        atexit.register(self.servicemanager.disconnect)

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, args.skipverification)

        # Default VM name
        self.vm_name = 'vm-' + str(generate_random_uuid())
Ejemplo n.º 6
0
 def capture_source_vm(self, vm_id, param):
     source = LibraryItem.DeployableIdentity(self.deployable_resource_type,
                                             vm_id)
     result = self.client.ovf_lib_item_service.create(
         source,
         param["target"],
         param["spec"],
         client_token=generate_random_uuid())
     return result.ovf_library_item_id
Ejemplo n.º 7
0
    def upload_files(self, library_item_id, files_map):
        """
        Upload a VM template to the published CL

        """
        # Create a new upload session for uploading the files
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=library_item_id),
            client_token=generate_random_uuid())
        self.upload_files_in_session(files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
Ejemplo n.º 8
0
    def _setup(self):
        self.cluster_name = self.args.clustername
        assert self.cluster_name is not None

        self.lib_item_name = self.args.libitemname
        assert self.lib_item_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)
        # Default VM name
        self.vm_name = 'vm-' + str(generate_random_uuid())
Ejemplo n.º 9
0
    def delete_and_upload_scenario(self, library_id):
        """
        :param library_id: the OVF item will be created and updated in this library
        :return: None

        Content update scenario 1:
        Update OVF library item by creating an update session for the
        OVF item, removing all existing files in the session, then
        adding all new files into the same update session, and completing
        the session to finish the content update.
        """

        # Create a new library item in the content library for uploading the files
        ovf_item_id = self.helper.create_library_item(
            library_id=library_id,
            item_name='demo-ovf-item',
            item_description='Sample simple VM template',
            item_type='ovf')
        assert ovf_item_id is not None
        print('Library item created id: {0}'.format(ovf_item_id))
        print('OVF Library item version (at creation) {0}:'.format(
            self.get_item_version(ovf_item_id)))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(
            ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=ovf_item_id,
                                 files_map=ovf_files_map)
        print('Uploaded ovf and vmdk files to library item {0}'.format(
            ovf_item_id))
        original_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (on original content upload): {0}'.
              format(original_version))

        # Create a new session and perform content update
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=ovf_item_id),
            client_token=generate_random_uuid())
        existing_files = self.client.upload_file_service.list(session_id)
        for file in existing_files:
            print('deleting {0}'.format(file.name))
            self.client.upload_file_service.remove(session_id, file.name)
        ovf_files_map = self.helper.get_ovf_files_map(
            ovf_location=ClsApiHelper.PLAIN_OVF_RELATIVE_DIR)
        self.helper.upload_files_in_session(ovf_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'
    def __init__(self):

        self.vm_name = 'deployed-vm-' + str(generate_random_uuid())

        parser = sample_cli.build_arg_parser()
        required_args = parser.add_argument_group('required arguments')
        required_args.add_argument(
            '--libitemname',
            required=True,
            help='The name of the library item to deploy. '
            'The library item should contain an OVF package.')

        parser.add_argument(
            '--vmname',
            default=self.vm_name,
            help='The name of the Virtual Machine to be deployed. '
            'Default: "{}"'.format(self.vm_name))

        parser.add_argument('--resourcepoolname',
                            default='Compute-ResourcePool',
                            help='The name of the resource pool to be used. '
                            'Default: "Compute-ResourcePool"')

        parser.add_argument('--foldername',
                            default='Workloads',
                            help='The name of the folder to be used. '
                            'Default: "Workloads"')

        parser.add_argument('--opaquenetworkname',
                            help='The name of the opaque network to be added '
                            'to the deployed vm')

        args = sample_util.process_cli_args(parser.parse_args())

        self.vm_id = None
        self.lib_item_name = args.libitemname
        self.vm_name = args.vmname
        self.resourcepoolname = args.resourcepoolname
        self.foldername = args.foldername
        self.opaquenetworkname = args.opaquenetworkname
        self.cleardata = args.cleardata

        # Connect to vAPI Endpoint on vCenter Server
        self.client = create_vsphere_client(server=args.server,
                                            username=args.username,
                                            password=args.password)
Ejemplo n.º 11
0
    def _execute(self):
        # List of visible content libraries
        visible_cls = self.client.local_library_service.list()
        if len(visible_cls) > 0:
            for visible_cl in visible_cls:
                get_visible_cl = self.client.local_library_service.get(
                    visible_cl)
                print('Visible content library: {0} with id: {1}'.format(
                    get_visible_cl.name, visible_cl))

        # Find the datastore by the given datastore name using property collector
        self.datastore_id = get_datastore_id(
            service_manager=self.servicemanager,
            datastore_name=self.datastore_name)
        assert self.datastore_id is not None
        print('DataStore: {0} ID: {1}'.format(self.datastore_name,
                                              self.datastore_id))

        # Build the storage backing for the library to be created
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE,
                                         datastore_id=self.datastore_id)
        storage_backings.append(storage_backing)

        # Build the specification for the library to be created
        create_spec = LibraryModel()
        create_spec.name = self.lib_name
        create_spec.description = "Local library backed by VC datastore"
        create_spec.type = create_spec.LibraryType.LOCAL
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore using vAPIs
        library_id = self.client.local_library_service.create(
            create_spec=create_spec, client_token=generate_random_uuid())
        print('Local library created: ID: {0}'.format(library_id))

        # Retrieve the local content library
        self.local_library = self.client.local_library_service.get(library_id)
        print('Retrieved library: ID: {0}'.format(self.local_library.id))

        # Update the local content library
        update_spec = LibraryModel()
        update_spec.description = "new description"
        self.client.local_library_service.update(library_id, update_spec)
        print('Updated library description')
Ejemplo n.º 12
0
    def create_published_library(self, pub_lib_name):
        pub_info = PublishInfo()
        pub_info.published = True
        # VMTX sync needs the authentication to be turned off
        pub_info.authentication_method = PublishInfo.AuthenticationMethod.NONE
        pub_spec = LibraryModel()
        pub_spec.name = pub_lib_name
        pub_spec.description = "Sample Published library"
        pub_spec.publish_info = pub_info
        pub_spec.type = pub_spec.LibraryType.LOCAL
        pub_spec.storage_backings = self.storage_backings

        pub_lib_id = self.client.local_library_service.create(
            create_spec=pub_spec, client_token=generate_random_uuid())
        print("Published library created, id: {0}".format(pub_lib_id))

        pub_lib = self.client.library_service.get(pub_lib_id)
        return pub_lib
Ejemplo n.º 13
0
    def create_local_library(self, storage_backings, lib_name):
        """
        :param storage_backings: Storage for the library
        :param lib_name: Name of the library
        :return: id of the created library
        """
        create_spec = LibraryModel()
        create_spec.name = lib_name
        create_spec.description = "Local library backed by VC datastore"
        create_spec.type = LibraryModel.LibraryType.LOCAL
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore
        library_id = self.client.local_library_service.create(
            create_spec=create_spec, client_token=generate_random_uuid())
        print('Local library created, ID: {0}'.format(library_id))

        return library_id
    def deploy_ovf_template(self, lib_item_id, ovf_summary, deployment_target):
        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=self.vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        result = self.client.ovf_lib_item_service.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print(
                'Deployment successful. Result resource: {0}, ID: {1}'.format(
                    result.resource_id.type, result.resource_id.id))
            self.vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

            # Power on the VM and wait  for the power on operation to be completed
            self.vm_obj = get_obj_by_moId(self.servicemanager.content,
                                          [vim.VirtualMachine], self.vm_id)
            assert self.vm_obj is not None
            poweron_vm(self.servicemanager.content, self.vm_obj)

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))
Ejemplo n.º 15
0
    def _execute(self):
        # Find the datastore by the given datastore name using property collector
        self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name)
        assert self.datastore_id is not None
        print('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))

        # Build the storage backing for the library to be created
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE, datastore_id=self.datastore_id)
        storage_backings.append(storage_backing)

        # Build the specification for the library to be created
        create_spec = LibraryModel()
        create_spec.name = self.lib_name
        create_spec.description = "Local library backed by VC datastore"
        create_spec.type = create_spec.LibraryType.LOCAL
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore using vAPIs
        library_id = self.client.local_library_service.create(create_spec=create_spec,
                                                              client_token=generate_random_uuid())
        print('Local library created: ID: {0}'.format(library_id))
        self.local_library = self.client.local_library_service.get(library_id)

        # Create a new library item in the content library for uploading the files
        self.library_item_id = self.helper.create_library_item(library_id=self.local_library.id,
                                                               item_name=self.lib_item_name,
                                                               item_description='Sample simple VM template',
                                                               item_type='ovf')
        assert self.library_item_id is not None
        assert self.client.library_item_service.get(self.library_item_id) is not None
        print('Library item created id: {0}'.format(self.library_item_id))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=self.library_item_id, files_map=ovf_files_map)
        print('Uploaded ovf and vmdk files to library item {0}'.format(self.library_item_id))

        # Download the library item from the CL
        temp_dir = tempfile.mkdtemp(prefix='simpleVmTemplate-')
        print('Downloading library item {0} to directory {1}'.format(self.library_item_id, temp_dir))
        downloaded_files_map = self.helper.download_files(library_item_id=self.library_item_id, directory=temp_dir)
        assert len(downloaded_files_map) == len(ovf_files_map)
Ejemplo n.º 16
0
    def replace_scenario(self, library_id):
        """
        :param library_id: the Iso item will be created, and then replaced in this library
        :return: None

        Content update scenario 2:
        Update ISO library item by creating an update session for the
        item, then adding the new ISO file using the same session file
        name into the update session, which will replace the existing
        ISO file upon session complete.
        """

        iso_item_id = self.helper.create_library_item(
            library_id=library_id,
            item_name=self.ISO_ITEM_NAME,
            item_description='Sample iso file',
            item_type='iso')
        print('ISO Library item version (on creation) {0}:'.format(
            self.get_item_version(iso_item_id)))

        iso_files_map = self.helper.get_iso_file_map(
            item_filename=self.ISO_FILE_1, disk_filename=self.ISO_FILE_1)
        self.helper.upload_files(library_item_id=iso_item_id,
                                 files_map=iso_files_map)
        original_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (on original content upload) {0}:'.
              format(original_version))

        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=iso_item_id),
            client_token=generate_random_uuid())
        # Use the same item filename (update endpoint, as it's a replace scenario)
        iso_files_map = self.helper.get_iso_file_map(
            item_filename=self.ISO_FILE_1, disk_filename=self.ISO_FILE_2)

        self.helper.upload_files_in_session(iso_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'
Ejemplo n.º 17
0
    def create_published_library(self, storage_backings):
        # Build the authenticated publish info.
        # Note: The username will be 'vcsp'.
        pub_info = PublishInfo()
        pub_info.published = True
        pub_info.authentication_method = PublishInfo.AuthenticationMethod.BASIC
        pub_info.password = self.DEMO_PASSWORD

        # Build the specification for the published library to be created
        pub_spec = LibraryModel()
        pub_spec.name = self.pub_lib_name
        pub_spec.description = "Published library backed by VC datastore"
        pub_spec.publish_info = pub_info
        pub_spec.type = pub_spec.LibraryType.LOCAL
        pub_spec.storage_backings = storage_backings

        pub_lib_id = self.client.local_library_service.create(
            create_spec=pub_spec, client_token=generate_random_uuid())

        return pub_lib_id
Ejemplo n.º 18
0
    def deploy_ovf_template(self, lib_item_id, ovf_summary, deployment_target,
                            vm_name):
        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True)

        # Deploy the ovf template
        result = self.client.ovf_lib_item_service.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())
        if result.succeeded:
            vm_id = result.resource_id.id
            return vm_id
        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))
            raise Exception('OVF deploy failed.')
Ejemplo n.º 19
0
    def create_subcribed_library(self, storage_backings, pub_lib_url):
        # Build the subscription information using the publish URL of the published
        # library. The username must be 'vcsp'.
        sub_info = SubscriptionInfo()
        sub_info.authentication_method = SubscriptionInfo.AuthenticationMethod.BASIC
        sub_info.user_name = self.VCSP_USERNAME
        sub_info.password = self.DEMO_PASSWORD
        sub_info.on_demand = False
        sub_info.automatic_sync_enabled = True
        sub_info.subscription_url = pub_lib_url

        # Build the specification for the subscribed library
        sub_spec = LibraryModel()
        sub_spec.name = self.sub_lib_name
        sub_spec.type = sub_spec.LibraryType.SUBSCRIBED
        sub_spec.subscription_info = sub_info
        sub_spec.storage_backings = storage_backings

        self.sub_lib_id = self.client.subscribed_library_service.create(
            create_spec=sub_spec, client_token=generate_random_uuid())
        sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
        return sub_lib, sub_spec
Ejemplo n.º 20
0
    def download_files(self, library_item_id, directory):
        """
        Download files from a library item

        Args:
            library_item_id: id for the library item to download files from
            directory: location on the client machine to download the files into

        """
        downloaded_files_map = {}
        # create a new download session for downloading the session files
        session_id = self.client.download_service.create(
            create_spec=DownloadSessionModel(library_item_id=library_item_id),
            client_token=generate_random_uuid())
        file_infos = self.client.download_file_service.list(session_id)
        for file_info in file_infos:
            self.client.download_file_service.prepare(session_id,
                                                      file_info.name)
            download_info = self.wait_for_prepare(session_id, file_info.name)
            if self.skip_verification and hasattr(
                    ssl, '_create_unverified_context'):
                # Python 2.7.9 has stronger SSL certificate validation,
                # so we need to pass in a context when dealing with self-signed
                # certificates.
                context = ssl._create_unverified_context()
                response = urllib2.urlopen(
                    url=download_info.download_endpoint.uri, context=context)
            else:
                # Don't pass context parameter since versions of Python
                # before 2.7.9 don't support it.
                response = urllib2.urlopen(download_info.download_endpoint.uri)
            file_path = os.path.join(directory, file_info.name)
            with open(file_path, 'wb') as local_file:
                local_file.write(response.read())
            downloaded_files_map[file_info.name] = file_path
        self.client.download_service.delete(session_id)
        return downloaded_files_map
    def setup(self):
        parser = sample_cli.build_arg_parser()
        parser.add_argument('-n',
                            '--vm_name',
                            action='store',
                            help='Name of the testing vm')
        parser.add_argument('-resourcepoolname',
                            '--resourcepoolname',
                            help='The name of the resource pool to be used.')
        parser.add_argument('-libitemname',
                            '--libitemname',
                            help='The name of the library item to deploy.'
                            'The library item should contain an OVF package.')
        parser.add_argument(
            '-vm_count',
            '--vm_count',
            help='Number of VMs to be created. By default is 1',
            type=int,
            default=1)
        args = sample_util.process_cli_args(parser.parse_args())
        self.lib_item_name = args.libitemname
        self.resource_pool_name = args.resourcepoolname
        self.vm_name = args.vm_name
        self.vm_count = args.vm_count

        self.servicemanager = ServiceManager(args.server, args.username,
                                             args.password,
                                             args.skipverification)
        self.servicemanager.connect()
        atexit.register(self.servicemanager.disconnect)

        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, args.skipverification)

        # Default VM name
        if not self.vm_name:
            self.vm_name = 'vm-' + str(generate_random_uuid())
    def deploy_ovf_template(self):

        # Build the deployment target with resource pool ID and folder ID
        rp_filter_spec = ResourcePool.FilterSpec(names=set([self.resourcepoolname]))
        resource_pool_summaries = self.client.vcenter.ResourcePool.list(rp_filter_spec)
        if not resource_pool_summaries:
            raise ValueError("Resource pool with name '{}' not found".
                             format(self.resourcepoolname))
        resource_pool_id = resource_pool_summaries[0].resource_pool
        print('Resource pool ID: {}'.format(resource_pool_id))

        folder_filter_spec = Folder.FilterSpec(names=set([self.foldername]))
        folder_summaries = self.client.vcenter.Folder.list(folder_filter_spec)
        if not folder_summaries:
            raise ValueError("Folder with name '{}' not found".
                             format(self.foldername))
        folder_id = folder_summaries[0].folder
        print('Folder ID: {}'.format(folder_id))

        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=resource_pool_id,
            folder_id=folder_id
        )

        # Find the library item
        find_spec = Item.FindSpec(name=self.lib_item_name)
        lib_item_ids = self.client.content.library.Item.find(find_spec)
        if not lib_item_ids:
            raise ValueError("Library item with name '{}' not found".
                             format(self.lib_item_name))
        lib_item_id = lib_item_ids[0]
        print('Library item ID: {}'.format(lib_item_id))
        ovf_summary = self.client.vcenter.ovf.LibraryItem.filter(
            ovf_library_item_id=lib_item_id,
            target=deployment_target)
        print('Found an OVF template: {} to deploy.'.format(ovf_summary.name))

        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=self.vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        result = self.client.vcenter.ovf.LibraryItem.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print('Deployment successful. VM Name: "{}", ID: "{}"'
                  .format(self.vm_name, result.resource_id.id))
            self.vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))

        # Add an opaque network portgroup to the deployed VM
        if self.opaquenetworkname:
            filter = Network.FilterSpec(
                names=set([self.opaquenetworkname]),
                types=set([Network.Type.OPAQUE_NETWORK]))
            network_summaries = self.client.vcenter.Network.list(filter=filter)
            if not network_summaries:
                raise ValueError("Opaque network {} can not find".format(
                    self.opaquenetworkname))
            network = network_summaries[0].network

            nic_create_spec = Ethernet.CreateSpec(
                start_connected=True,
                mac_type=Ethernet.MacAddressType.GENERATED,
                backing=Ethernet.BackingSpec(
                    type=Ethernet.BackingType.OPAQUE_NETWORK,
                    network=network))
            print('vm.hardware.Ethernet.create({}, {}) -> {}'.format(
                self.vm_id, nic_create_spec, network))
            nic = self.client.vcenter.vm.hardware.Ethernet.create(
                self.vm_id, nic_create_spec)

            nic_info = self.client.vcenter.vm.hardware.Ethernet.get(self.vm_id, nic)
            print('vm.hardware.Ethernet.get({}, {}) -> {}'.format(
                self.vm_id, nic, pp(nic_info)))
Ejemplo n.º 23
0
    def deploy_ovf_template(self):

        # Build the deployment target with resource pool ID
        filter_spec = ResourcePool.FilterSpec(
            names=set([self.resourcepoolname]))
        resource_pool_summaries = self.client.vcenter.ResourcePool.list(
            filter_spec)
        if not resource_pool_summaries:
            raise ValueError("Resource pool with name '{}' not found".format(
                self.resourcepoolname))
        resource_pool_id = resource_pool_summaries[0].resource_pool
        print('Resource pool ID: {}'.format(resource_pool_id))
        deployment_target = LibraryItem.DeploymentTarget(
            resource_pool_id=resource_pool_id)

        # Find the library item
        find_spec = Item.FindSpec(name=self.lib_item_name)
        lib_item_ids = self.client.content.library.Item.find(find_spec)
        if not lib_item_ids:
            raise ValueError("Library item with name '{}' not found".format(
                self.lib_item_name))
        lib_item_id = lib_item_ids[0]
        print('Library item ID: {}'.format(lib_item_id))
        ovf_summary = self.client.vcenter.ovf.LibraryItem.filter(
            ovf_library_item_id=lib_item_id, target=deployment_target)
        print('Found an OVF template: {} to deploy.'.format(ovf_summary.name))

        # Build the deployment spec
        deployment_spec = LibraryItem.ResourcePoolDeploymentSpec(
            name=self.vm_name,
            annotation=ovf_summary.annotation,
            accept_all_eula=True,
            network_mappings=None,
            storage_mappings=None,
            storage_provisioning=None,
            storage_profile_id=None,
            locale=None,
            flags=None,
            additional_parameters=None,
            default_datastore_id=None)

        # Deploy the ovf template
        result = self.client.vcenter.ovf.LibraryItem.deploy(
            lib_item_id,
            deployment_target,
            deployment_spec,
            client_token=generate_random_uuid())

        # The type and ID of the target deployment is available in the deployment result.
        if result.succeeded:
            print('Deployment successful. Result resource: {}, ID: {}'.format(
                result.resource_id.type, result.resource_id.id))
            self.vm_id = result.resource_id.id
            error = result.error
            if error is not None:
                for warning in error.warnings:
                    print('OVF warning: {}'.format(warning.message))

        else:
            print('Deployment failed.')
            for error in result.error.errors:
                print('OVF error: {}'.format(error.message))