You can create VM and OVF templates from virtual machines and vApps in your inventory. You can then deploy virtual machines and vApps from the templates that are stored in a content library.

Create a VM Template in a Content Library from a Virtual Machine

By using the vSphere Automation API, you can create a VM template in a content library from an existing virtual machine in your vCenter Server inventory.

When you call the create function of the com.vmware.vcenter.vm_template.LibraryItems service, a VM template is created as a library item in your local content library. If the operation is successful, the LibraryItems service returns the ID of the newly created library item.

To create a library item that contains a VM template, you can use the ctreate function of the LibraryItems interface. You can review the information about a VM template by using the get function of the LibraryItems interface. For information about how to create a VM template by using the vSphere Client, see the vSphere Virtual Machine Administration documentation.

For information about the available and mandatory parameters, see the API Reference documentation.

Prerequisites

  • Verify that you have administrative privileges on your vCenter Server instance.
  • Verify that you created a vSphere Automation session to your vCenter Server.
  • Verify that you created a local library by using the vSphere Client or the vSphere Automation APIs.

Procedure

  1. Get the ID of your ESXi host on which you want to store the VM template.

    You can use the list function of the com.vmware.vcenter.Host interface.

  2. Get the ID of the datastore on which you want to store the VM template files.

    You can use the list function of the com.vmware.vcenter_client.Datastore interface.

  3. Get the ID of the virtual machine that you want to save as a VM template.

    You can use the list method of the com.vmware.vcenter_client.VM interface.

  4. Get the ID of your local library.

    You can get the list of the local libraries in your vCenter Server and review the information about each library by using the list and get(library_id) functions of the com.vmware.content_client.LocalLibrary class.

  5. Create a library item specification for the VM template.
    You can use the com.vmware.vcenter.vm_template.LibraryItems.CreateSpec class.
    1. Specify the local library, source virtual machine, and the name of the library item by using the library, source_vm, and name parameters. You must use the IDs of the local library and source virtual machine.
    2. Specify the placement information for your VM template.
      You can use the LibraryItems.CreatePlacementSpec class. To specify the host, resource pool, cluster, and folder, you must use their IDs.
    3. Specify the datastore on which you want to store the log, configuration, and disk files of your VM template.
      To specify the storage backing for the VM template, you can use the com.vmware.vcenter.vm_template.LibraryItems.CreateSpecVmHomeStorage and com.vmware.vcenter.vm_template.LibraryItems.CreateSpecDiskStorage classes. You must use the ID of the datastore.
    4. Include the placement and storage specifications in the library item specification.
  6. Create a library item for storing the VM template.
    You can use the create(spec) function of the com.vmware.vcenter.vm_template.LibraryItems interface.

Results

If the operation is successful, the LibraryItems service returns the ID of the library item that contains the VM template. For information about the available responses, see the API Reference documentation.

What to do next

  • Review the information stored in the library item by using the get(VM_template_item_ID) function of the com.vmware.vcenter.vm_template.LibraryItems interface. If you did not save the ID of the library item holding the VM template, you can check the UUID by using the vSphere Client. The URN ends with the ID of the library item and has the following format: urn:vapi:com.vmware.content.library.Item:<VMTemplateItemID>.

Python Example of Creating a VM Template in a Content Library from a Virtual Machine

This example shows how you can create a VM template from a virtual machine and add the template to a content library by using the vSphere Automation API. The example is based on the create_vm_template.py sample.

Note: For a complete and up-to-date version of the sample code, see the vsphere-automation-sdk-python VMware repository at GitHub.
class CreateVmTemplate(SampleBase):
	...
    def _setup(self):
        # Required arguments
        self.vm_name = self.args.vmname
        self.datacenter_name = self.args.datacentername
        self.resource_pool_name = self.args.resourcepoolname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.item_name = (self.args.itemname if self.args.itemname
                          else rand('vmtx-item-'))

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        # Get the identifiers for the virtual machine and resource pool
        vm_id = get_vm(self.vsphere_client, self.vm_name)
        assert vm_id
        resource_pool_id = get_resource_pool(self.vsphere_client,
                                             self.datacenter_name,
                                             self.resource_pool_name)
        assert resource_pool_id

        # Create a local content library
        storage_backings = self.helper.create_storage_backings(self.servicemanager,
                                                               self.datastore_name)
        self.library_id = self.helper.create_local_library(storage_backings,
                                                           self.library_name)

        # Build the library item create specification
        create_spec = VmtxLibraryItem.CreateSpec()
        create_spec.source_vm = vm_id
        create_spec.library = self.library_id
        create_spec.name = self.item_name
        create_spec.placement = VmtxLibraryItem.CreatePlacementSpec(resource_pool=resource_pool_id)

        # Create a new library item from the source virtual machine
        self.item_id = self.client.vmtx_service.create(create_spec)
	...

Create an OVF Template in a Content Library from a Virtual Machine or vApp

You can create library items from existing virtual machines or vApp. Use those library items later to deploy virtual machines and vApps on hosts and clusters in your vCenter Server environment.

Procedure

  1. Create a com.vmware.vcenter.ovf.LibraryItemTypes.DeployableIdentity instance to specify the source virtual machine or vApp to be captured in an OVF template.
  2. Create a com.vmware.vcenter.ovf.LibraryItemTypes.CreateTarget instance to identify the content library where the OVF template is stored.
  3. Create a com.vmware.vcenter.ovf.LibraryItemTypes.CreateSpec instance to specify the properties of the OVF template.
  4. Initiate a synchronous create operation by invoking the create function of the com.vmware.vcenter.ovf.LibraryItem service.
  5. Verify the outcome of the create operation.

Java Example of Creating an OVF Template in a Content Library from a Virtual Machine

This example shows how to capture a virtual machine in an OVF template and store the file in a new library item in a specified library.

This example uses the steps that are described in the Create an OVF Template in a Content Library from a Virtual Machine or vApp procedure.

Note: For related code samples, see the vsphere-automation-sdk-java VMware repository at GitHub.
...
 
// Specify the resource to be captured.
LibraryItemTypes.DeployableIdentity deployableIdentity = new LibraryItemTypes.DeployableIdentity();
deployableIdentity.setType("VirtualMachine");
deployableIdentity.setId("vm-32");
 
// Create a target spec to identify a library to hold the new item.
LibraryItemTypes.CreateTarget createTarget = new LibraryItemTypes.CreateTarget();
createTarget.setLibraryId(myLibraryId);
 
// Specify OVF properties.
LibraryItemTypes.CreateSpec createSpec = new LibraryItemTypes.CreateSpec();
createSpec.setName("snap-32");
createSpec.setDescription("Snapshot of VM-32");
 
// Initiate synchronous capture operation.
LibraryItem itemStub = myStubFactory.createStub(LibraryItem.class, myStubConfiguration);
String clientToken = UUID.randomUUID().toString();
LibraryItemTypes.CreateResult result = itemStub.create(clientToken, deployableIdentity, createTarget, createSpec);
 
// Verify capture status.
System.out.printf("Resource Type=%s (ID=%s) status:",
                  deployableIdentity.getType(),
                  deployableIdentity.getId());
  if (result.getSucceeded() == true) {
     System.out.println("Resource captured.");

  }else {
     System.out.println("Capture failed.");
  }
  
  if (result.getError() != null) {
    
    for (OvfError error : result.getError().getErrors()) {
        System.out.printf("Error: %s", error.getMessage().toString());
    }
  
    for (OvfWarning warning : result.getError().getWarnings()) {
        System.out.printf("Warning: %s", warning.getMessage().toString());
    }
  
    for (OvfInfo info : result.getError().getInformation()) {
        List<LocalizableMessage> messages = info.getMessage();
    }

    for (LocalizableMessage message : messages) {
      System.out.printf("Message: %s", message.toString());
    }
  }

Python Example of Creating an OVF Template in a Content Library from a Virtual Machine

This example shows how to capture a virtual machine in an OVF template and store the files in a new library item in a specified library.

This example uses the steps that are described in the Create an OVF Template in a Content Library from a Virtual Machine or vApp procedure.

Note: For related code samples, see the vsphere-automation-sdk-python VMware repository at GitHub.
...
 
# Specify the resource to be captured.
deployable_identity = ovf_client.LibraryItem.DeployableIdentity();
deployable_identity.type = “VirtualMachine”
deployable_identity.id = “vm-32”
 
# Create a target spec to identify a library to hold the new item.
create_target = ovf_client.LibraryItem.CreateTarget()
create_target.library_id = my_library_id
 
# Specify OVF properties.
create_spec = ovf_client.LibraryItem.CreateSpec()
create_spec.name = “snap-32”
create_spec.description = “Snapshot of VM-32”
 
# Initiate synchronous capture operation.
lib_item_stub = ovf_client.LibraryItem(my_stub_config)
client_token = str(uuid.uuid4())
result = lib_item_stub.create(source=deployable_identity,
                              target=create_target,
                              create_spec=create_spec,
                              client_token=client_token)
 
# Verify capture status.
print("Resource Type={} (ID={}) status:".format(deployable_identity.type, deployable_identity.id))
 
if result.succeeded == True :
  print("Resource captured.”)
else :
  print("Capture failed.")
if result.error is not None :
  for error in result.error.errors :
    print("Error {}".format(error.message))
  if len(result.error.warnings) > 0 :
    print("Warnings:")
    for warning in result.error.warnings :
      print("{}".format(warning.message))
  if len(result.error.information) > 0 :
    print("Messages:")
    for info in result.error.information :
      for message in info.messages :
        print("{}".format(message))

Deploy a Virtual Machine from a VM Template in a Content Library

By using the vSphere Automation APIs, you can deploy a virtual machine from a VM template stored in a content library.

To deploy a virtual machine from a VM template in a content library, call the deploy function of the com.vmware.vcenter.vm_template.LibraryItems interface. You can specify the power state and customize the guest operation system prior to the virtual machine deployment.

For information about the available and mandatory parameters, see the API Reference documentation.

Prerequisites

  • Verify that you have administrative privileges on your vCenter Server instance.
  • Verify that you created a vSphere Automation session to your vCenter Server instance.

Procedure

  1. Review the information stored in the VM template library item.
    You can use the get(VM_template_item_ID) function of the com.vmware.vcenter.vm_template.LibraryItems interface and pass the ID of your VM template item. If you did not save the ID of your item, you can select the UUID of your VM template item by using the vSphere Client. The URN ends with the ID of the item and has the following format: urn:vapi:com.vmware.content.library.Item:<VMTemplateItemID>.
  2. Get the ID of the host on which you want to deploy the virtual machine.
    You can use the list function of the com.vmware.vcenter.Host interface.
  3. Get the ID of the resource pool to which you want to add your virtual machine.
    You can use the list function of the com.vmware.vcenter.ResourcePool interface.
  4. Get the ID of the VIRTUAL_MACHINE folder to which you want to add your virtual machine.
    You can use the list function of the com.vmware.vcenter.Folder.
  5. Get the ID of the datastore on which you want to store log, configuration, and disk files of the virtual machine.
    You can use the list function of the com.vmware.vcenter.Datastore interface.
  6. Create a deployment specification.
    You can use the com.vmware.vcenter.vm_template.LibraryItems.DeploySpec class.
    1. Specify a name and description of the virtual machine that you want to deploy.
    2. Specify the place in your inventory on which you want to deploy the virtual machine such as an ESXi host, resource pool, and VM folder.
      You can use the com.vmware.vcenter.vm_template.LibraryItems.DeployPlacementSpec class. You must use the IDs of your inventory objects.
    3. Specify the datastore on which you want to store the log, configuration, and disk files of the virtual machine. You must use the ID of the datastore.
      You can use the DeploySpecVmHomeStorage and DeploySpecDiskStorage classes.
    4. (Optional) Specify the guest operating system and hardware customization specifications that you want to apply to the virtual machine during the deployment process. Add this information to the deployment specification.
      You can use the GuestCustomizationSpec and HardwareCustomizationSpec classes. You can get a list of the guest operating system customization specifications that are available in your vCenter Server by using the list function of the com.vmware.vcenter.guest.CustomizationSpecs interface.
    5. Include the placement and storage specifications in the deployment specification.
  7. Deploy a virtual machine from your VM template.
    You can use the deploy(template_library_item, spec) function of the com.vmware.vcenter.vm_template.LibraryItems interface by passing the library item ID where the VM template is stores and the deployment specification.

Results

If the operation is successful, the ID of the deployed virtual machine is returned. For information about the possible exceptions, see the API Reference documentation.

Python Example of Deploying a VM from a VM Template Library Item

This example shows how you can deploy a VM from a VM Template library item by using the API. The example is based on the deploy_vm_template.py sample.

Note: For a complete and up-to-date version of the sample code, see the vsphere-automation-sdk-python VMware repository at GitHub.
class DeployVmTemplate(SampleBase):
	...
    def _setup(self):
        # Required arguments
        self.item_name = self.args.itemname
        self.datacenter_name = self.args.datacentername
        self.folder_name = self.args.foldername
        self.resource_pool_name = self.args.resourcepoolname
        self.datastore_name = self.args.datastorename

        # Optional arguments
        self.vm_name = self.args.vmname if self.args.vmname else rand('vm-')

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

        session = get_unverified_session() if self.skip_verification else None
        self.vsphere_client = create_vsphere_client(server=self.server,
                                                    username=self.username,
                                                    password=self.password,
                                                    session=session)

    def _execute(self):
        # Get the identifiers of the resources used for deployment
        item_id = self.helper.get_item_id_by_name(self.item_name)
        assert item_id
        folder_id = get_folder(self.vsphere_client,
                               self.datacenter_name,
                               self.folder_name)
        assert folder_id
        resource_pool_id = get_resource_pool(self.vsphere_client,
                                             self.datacenter_name,
                                             self.resource_pool_name)
        assert resource_pool_id
        datastore_id = get_datastore_id(self.servicemanager,
                                        self.datastore_name)
        assert datastore_id

        # Build the deployment specification
        placement_spec = VmtxLibraryItem.DeployPlacementSpec(
            folder=folder_id,
            resource_pool=resource_pool_id)
        vm_home_storage_spec = VmtxLibraryItem.DeploySpecVmHomeStorage(
            datastore=datastore_id)
        disk_storage_spec = VmtxLibraryItem.DeploySpecDiskStorage(
            datastore=datastore_id)
        deploy_spec = VmtxLibraryItem.DeploySpec(
            name=self.vm_name,
            placement=placement_spec,
            vm_home_storage=vm_home_storage_spec,
            disk_storage=disk_storage_spec)

        # Deploy a virtual machine from the VM template item
        self.vm_id = self.client.vmtx_service.deploy(item_id, deploy_spec)
        self.vm = get_obj_by_moId(self.servicemanager.content,
                                  [vim.VirtualMachine], self.vm_id)
	...

Deploy a Virtual Machine or vApp from an OVF Template in a Content Library

You can use the com.vmware.vcenter.ovf.LibraryItem service to deploy a virtual machine or vApp on a host, cluster, or resource pool from a library item.

Procedure

  1. Create a com.vmware.vcenter.ovf.LibraryItemTypes.DeploymentTarget instance to specify the deployment location of the virtual machine or vApp.
  2. Create a com.vmware.vcenter.ovf.LibraryItemTypes.ResourcePoolDeploymentSpec instance to define all necessary parameters for the deployment operation.
    For example, you can assign a name for the deployed virtual machine or vApp, and accept the End User License Agreements (EULAs) to complete the deployment successfully.
  3. (Optional) Retrieve information from the descriptor file of the OVF template and use the information during the OVF template deployment.
  4. Call the deploy method on the LibraryItem service.
  5. Verify the outcome of the deployment operation.

Java Example of Deploying a Virtual Machine from a Library Item in a Resource Pool

This example shows how to deploy a virtual machine from a local library item in a resource pool. You can also see how to verify the results of the deployment operation.

This example uses the steps that are described in the Deploy a Virtual Machine or vApp from an OVF Template in a Content Library procedure.

Note: For related code samples, see the vsphere-automation-sdk-java VMware repository at GitHub.
...

// Create a virtual machine deployment specification to accept any network resource.
ResourcePoolDeploymentSpec deploymentSpec = new ResourcePoolDeploymentSpec();
String vmName = "MyVirtualMachine"; 
deploymentSpec.setName(vmName);
deploymentSpec.setAcceptAllEULA(true);

 
// Create a deployment target specification to accept any resource pool.
String clusterName = "myCluster";
ManagedObjectReference clusterMoRef = VimUtil.getCluster(this.vimAuthHelper.getVimPort(), this.vimAuthHelper.getServiceContent(), clusterName);
DeploymentTarget deploymentTarget = new DeploymentTarget();
deploymentTarget.setResourcePoolId(clusterMoRef.getValue());


// Retrieve the library items OVF information and use it for populating the 
// deployment spec instance.
LibraryItem libItemStub = stubFactory.createStub(LibraryItem.class, myStubConfiguration);
OvfSummary ovfSummary = libItemStub.filter(libItemId, deploymentTarget);
deploymentSpec.setAnnotation(ovfSummary.getAnnotation());
String clientToken = UUID.randomUUID().toString();
DeploymentResult result = libItemStub.deploy(clientToken,libItemId,
                                                           deploymentTarget,
                                                           deploymentSpec);
 
// Verify the status of the resource deployment.
System.out.printf("Resource Type=%s (ID=%s) status: ",
                  result.getResourceId().getType(),
                  result.getResourceId().getId());
  
  if (result.getSucceeded() == true) {
      System.out.println("Resource instantiated.");
  
  } else {
      System.out.println("Instantiation failed.");
  }

Python Example of Deploying a Virtual Machine from a Library Item on a Resource Pool

This example is based on the deploy_ovf_template.py sample file.

This example uses the steps that are described in the Deploy a Virtual Machine or vApp from an OVF Template in a Content Library procedure.

Note: For a complete and up-to-date version of the sample code, see the vsphere-automation-sdk-python VMware repository at GitHub.
...
 
# Create a VM deployment specification to accept any network resource.
deployment_spec = ovf_client.LibraryItem.ResourcePoolDeploymentSpec()
deployment_spec.accept_all_eula = True
 
# Create deployment target spec to accept any resource pool.
target_spec = ovf_client.LibraryItem.DeploymentTarget()
 
# Initiate synchronous deployment operation.
item_stub = ovf_client.LibraryItem(my_stub_config)
result = item_stub.deploy(my_library_item_id,
                          target_spec,
                          deployment_spec,
                          client_token=str(uuid.uuid4())
 
# Verify deployment status.
print("Resource Type={} (ID={}) status:".format(result.resource_id.type, result.resource_id.id))
if result.succeeded == True :
  print("Resource instantiated.”)
else :
  print("Instantiation failed.")
if result.error is not None :
  for error in result.error.errors :
    print("Error {}".format(error.message))
  if len(result.error.warnings) > 0 :
    print("Warnings:")
    for warning in result.error.warnings :
      print("{}".format(warning.message))
  if len(result.error.information) > 0 :
    print("Messages:")
    for info in result.error.information :
      for message in info.messages :
        print("{}".format(message))