Vsphere Automation SDK 801 Programming Guide
Vsphere Automation SDK 801 Programming Guide
Automation SDKs
Programming Guide
Update 1
VMware vSphere 8.0
VMware ESXi 8.0
vCenter Server 8.0
VMware vSphere Automation SDKs Programming Guide
You can find the most up-to-date technical documentation on the VMware website at:
https://docs.vmware.com/
VMware, Inc.
3401 Hillview Ave.
Palo Alto, CA 94304
www.vmware.com
©
Copyright 2015-2023 VMware, Inc. All rights reserved. Copyright and trademark information.
VMware, Inc. 2
Contents
4 Authentication Mechanisms 28
Authentication Terminolgy 29
Create a vSphere Automation Session with User Credentials 31
Java Example of Creating a vSphere Automation API Session with User Credentials 32
Python Example of Creating a vCloud Suite Session with Username and Password 33
Retrieve a SAML Token 34
Java Example of Retrieving a SAML Token 34
Python Example of Retrieving a SAML Token 35
Create a vSphere Automation Session with a SAML Token 35
Java Example of Creating a vSphere Automation API Session with a SAML Token 36
VMware, Inc. 3
VMware vSphere Automation SDKs Programming Guide
Python Example of Creating a vSphere Automation API Session with a SAML Token 37
Create a Web Services Session 38
Java Example of Creating a vSphere Web Services Session 39
Python Example of Creating a Web Services Session 39
Identity Provider Federation for vCenter Server 40
Federate vCenter Server to Microsoft Active Directory Federation Services (AD FS) 41
6 ESXi Hosts 50
Retrieving Information About ESXi Hosts 50
Adding a Standalone ESXi Host to vCenter Server 51
Disconnecting and Reconnecting ESXi Hosts 51
Configuring ESXi Entropy 51
VMware, Inc. 4
VMware vSphere Automation SDKs Programming Guide
VMware, Inc. 5
VMware vSphere Automation SDKs Programming Guide
VMware, Inc. 6
VMware vSphere Automation SDKs Programming Guide
Enable vSphere with Tanzu on a Cluster with the vSphere Networking Stack 190
Upgrading a Supervisor 194
Monitoring the Enable and Upgrade Supervisor Operations 195
Reconfiguring a Supervisor 195
Disabling a Supervisor 195
Content Libraries in vSphere with Tanzu 196
Creating, Securing, and Synchronizing Content Libraries for Tanzu Kubernetes Releases
196
Creating and Managing Content Libraries for VM Provisioning in vSphere with Tanzu 198
Associating a Content Library with a Namespace 198
Managing Namespaces on a Supervisor 199
Create a vSphere Namespace 199
Updating the Namespace Configuration 202
Configuring the Access to a Namespace 202
Self-Service Namespace Management 203
Virtual Machines in vSphere with Tanzu 204
Create a VM Class in vSphere with Tanzu 205
Editing or Removing a VM Class from Your Environment 206
Associating a VM Class with a vSphere Namespace 207
VMware, Inc. 7
VMware vSphere Automation SDKs Programming Guide
VMware, Inc. 8
About vSphere Automation SDKs
Programming Guide
VMware vSphere Automation SDKs Programming Guide provides information about how to use
®
the VMware vSphere Automation™ SDK to automate different vSphere management tasks.
At VMware, we value inclusion. To foster this principle within our customer, partner, and internal
community, we have updated this guide to remove instances of non-inclusive language.
Intended Audience
This manual is intended for anyone who wants to develop applications for accessing and using
vSphere features such as virtual machine management, tagging, content libraries, managing the
life cycle of clusters with the vSphere Lifecycle Manager, vSphere with Tanzu, and so on. The
information is written for developers who have understanding of the targeted vSphere features
and some experience with Java and Python programming languages.
VMware, Inc. 9
Introduction to the vSphere
Automation SDKs 1
The vSphere Automation SDKs bundle client libraries for accessing new vSphere features
such as using content libraries and existing features such as virtual machine configuration and
management, vSphere tags and attributes, and so on.
The vSphere Automation SDKs contain sample applications and API reference documentation for
the vSphere services that are accessible via the vSphere Automation API endpoint. The vSphere
Automation SDKs also provide sample code that demonstrates how you can establish a secure
connection with the vSphere Automation API endpoint and access the available vSphere services
for working with vSphere objects.
vSphere Automation SDKs support two programming languages for developing client
applications for managing components in your virtual environment by accessing the vSphere
Automation API services.
Client applications use the vSphere Automation API to communicate with infrastructure and
management vCenter Server services.
VMware, Inc. 10
VMware vSphere Automation SDKs Programming Guide
Figure 1-1. Communication Model Between a Client Application and the vSphere Automation API
Retrieve service
endpoint
Lookup Service
Establish
authenticated
session
vCenter Single Sign-On
Communicate
with services
Client vSphere Automation API Endpoint
Application
vCenter Server
Client applications use the Lookup Service to retrieve the vCenter Single Sign-On endpoint, the
vSphere Automation API endpoint, and the endpoints of services that are exposed through the
®
VMware vSphere API. To access vSphere Automation services such as those for managing
content libraries and vSphere tags, client applications send requests to the vSphere Automation
API endpoint. By using the vCenter Single Sign-On service, client applications can either establish
an authenticated vSphere Automation session, or authenticate individual requests to the vSphere
Automation API endpoint.
Client applications can access services that are exposed through the vSphere Web Services API
®
by using the VMware vSphere Management SDK.
VMware, Inc. 11
VMware vSphere Automation SDKs Programming Guide
API Explorer
The API Explorer is a VMware utility similar to the Managed Object Browser (MOB). Access
the API Explorer at https://<vcenter_ip_address_or_fqdn>/apiexplorer or from the API
Explorer tab of the Developer Center pane in vSphere Client. Use the utility to connect to the
vSphere Automation API endpoint, browse through the available vSphere REST APIs, and make
calls to your vCenter Server instance.
SDK Samples
The vSphere Automation SDKs provide code samples that demonstrate how the vSphere
Automation API work and how they interoperate with the vSphere Web Services API. The code
snippets included in this documentation are based on the samples in the vSphere Automation
SDKs.
VMware, Inc. 12
Components of the vSphere
Automation Virtualization Layer 2
At the core of vSphere Automation is vSphere, which provides the virtualization layer of the
software-defined data center. You can use vSphere deployment options for vCenter Server and
ESXi hosts to build virtual environments of different scales.
In the client applications that use the vSphere Automation API, you use the vCenter Single
Sign-On and the Lookup Service on the vCenter Server to provide a range of functionality.
Service Discovery
VMware, Inc. 13
VMware vSphere Automation SDKs Programming Guide
You use the Lookup Service to retrieve the endpoint URL for the vCenter Single Sign-On
service on the vCenter Server, the location of the vCenter Server instances, and the vSphere
Automation API endpoint.
You can use the vSphere Automation API endpoint to access the following services running on
vCenter Server.
Content Library
You can use content libraries to share virtual machines, vApps, and other files, such as ISO,
OVA, and text files, across the software-defined data center. You can create, share, and
subscribe to content libraries on the same vCenter Server instance or on a remote instance.
Sharing content libraries promotes consistency, compliance, efficiency, and automation in
deploying workloads at scale.
You can also create OVF and VM templates from virtual machines and vApps in hosts,
resource pools, and clusters. You can then use the OVF and VM templates to deploy new
virtual machines and vApps.
Starting with vSphere 7.0, you can edit the contents of a VM template. You can check out the
library item that contains the VM template. After editing the VM template, check in the library
item to save the changes to the virtual machine.
Virtual Machine
You can use the vSphere Automation APIs to create, configure, and manage the life cycle of
virtual machines in your environment.
Starting with vSphere 7.0, you can also clone, create an instant clone, migrate, register, and
unregister a virtual machine.
vSphere Tags
VMware, Inc. 14
VMware vSphere Automation SDKs Programming Guide
With vSphere tags you can attach metadata to vSphere objects, and as a result, make it
easier to filter and sort these objects. You can use the vSphere Automation APIs to automate
the management of vSphere tags.
Starting with vSphere 7.0, you can enable vSphere with Tanzu on an existing vSphere cluster
in your environment. Create and configure namespaces on the Supervisors to run Kubernetes
workloads in dedicated resource pools.
VMware, Inc. 15
Retrieving Service Endpoints
3
To access services and resources in the virtual environment, client applications that use the
vSphere Automation API must know the endpoints of vSphere Automation and vSphere services.
Client applications retrieve service endpoints from the Lookup Service that runs on vCenter
Server.
The Lookup Service provides service registration and discovery by using the vSphere Web
Services API. By using the Lookup Service, you can retrieve endpoints of services on vCenter
Server. The following endpoints are available from the Lookup Service.
n The vCenter Single Sign-On endpoint on vCenter Server. You can use the vCenter Single
Sign-On service to get a SAML token and establish an authenticated session with a vSphere
Automation API endpoint or a vCenter Server endpoint.
n The vSphere Automation API endpoint on vCenter Server. Through the vSphere Automation
endpoint, you can make requests to vSphere Automation API services such as virtual machine
management, Content Library, and Tagging.
n The vCenter Server endpoint. In case you want to retrieve service endpoints on a vCenter
Server instance that is part of a vCenter Enhances Linked Mode group, use the vCenter
Server endpoint to get the node IDs of all linked instances. You can use the node ID of the
specific vCenter Server instance to retrieve service endpoints on that instance.
n The vSphere Web Services API endpoint and endpoints of other vSphere Web services that
run on vCenter Server.
1 Connect to the Lookup Service on vCenter Server and service registration object so that you
can query for registered services.
2 Create a service registration filter for the endpoints that you want to retrieve.
3 Use the filter to retrieve the registration information for services from the Lookup Service.
VMware, Inc. 16
VMware vSphere Automation SDKs Programming Guide
4 Extract one or more endpoint URLs from the array of registration information that you
receive from the Lookup Service.
n Connect to the Lookup Service and Retrieve the Service Registration Object
Optionally, you can include the node ID parameter in the filter to identify the vCenter Server
instance where the endpoint is hosted. When the node ID is omitted, the List() function returns
the set of endpoint URLs for all instances of the service that are hosted on different vCenter
Server instances in the environment.
VMware, Inc. 17
VMware vSphere Automation SDKs Programming Guide
For information about the filter parameter of the available predefined service endpoints, see
Filter Parameters for Predefined Service Endpoints.
Table 3-2. Input Data for URL Retrieval for the Lookup Service Registration Filter
protocol wsTrust
protocol vapi.json.https.public
protocol vmomi
protocol https
VMware, Inc. 18
VMware vSphere Automation SDKs Programming Guide
Table 3-2. Input Data for URL Retrieval for the Lookup Service Registration Filter (continued)
protocol https
protocol vmomi
Procedure
a Configure a connection stub for the Lookup Service endpoint, which uses SOAP bindings,
by using the HTTPS protocol.
With the service registration object, you can make registration queries.
VMware, Inc. 19
VMware vSphere Automation SDKs Programming Guide
This example uses the steps that are described in the Connect to the Lookup Service and
Retrieve the Service Registration Object procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
Note The connection code in the example disables certificate and host name checking for the
connection for simplicity. For a production deployment, supply appropriate handlers. See the
SDK sample file for a more detailed example of connection code.
...
String lookupServiceUrl;
LsService lookupService;
LsPortType lsPort;
ManagedObjectReference serviceInstanceRef;
LookupServiceContent lookupServiceContent;
ManagedObjectReference serviceRegistration;
HttpsURLConnection.setDefaultHostnameVerifier(hostVerifier);
SslUtil.trustAllHttpsCertificates();
((BindingProvider)lsProvider).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERT
Y, lookupServiceUrl);
...
VMware, Inc. 20
VMware vSphere Automation SDKs Programming Guide
This example uses the steps that are described in the Connect to the Lookup Service and
Retrieve the Service Registration Object procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
Prerequisites
Procedure
VMware, Inc. 21
VMware vSphere Automation SDKs Programming Guide
Option Description
Omit the node ID parameter Retrieves the endpoint URLs of the service on all vCenter Server instances.
Include the node ID parameter Retrieves the endpoint URL of the service on a particular vCenter Server
instance.
Results
Depending on whether you included the node ID parameter, the List() function returns one of
the following results:
n A list of endpoint URLs for a service that is hosted on all vCenter Server instances in the
environment.
What to do next
Call the function that you implemented to retrieve service endpoints. You can pass different filter
parameters depending on the service endpoints that you need. For more information, see Filter
Parameters for Predefined Service Endpoints.
To retrieve a service endpoint on a particular vCenter Server instance, you must retrieve the
node ID of that instance and pass it to the function. For information about how to retrieve the ID
of a vCenter Server instance, see Retrieve a vCenter Server ID by Using the Lookup Service.
This example uses the steps that are described in the Retrieve Service Endpoints on vCenter
Server Instances procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
/**
* Define filter criterion for retrieving a service endpoint.
* Omit the nodeID parameter to retrieve the endpoints hosted
* on all vCenter Server instances in the environment.
*/
VMware, Inc. 22
VMware vSphere Automation SDKs Programming Guide
String proto,
String epType,
String nodeID){
LookupServiceRegistrationServiceType filterServiceType =
new
LookupServiceRegistrationServiceType();
filterServiceType.setProduct(prod);
filterServiceType.setType(svcType);
LookupServiceRegistrationEndpointType filterEndpointType =
new
LookupServiceRegistrationEndpointType();
filterEndpointType.setProtocol(proto);
filterEndpointType.setType(epType);
...
This example uses the steps that are described in the Retrieve Service Endpoints on vCenter
Server Instances procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
VMware, Inc. 23
VMware vSphere Automation SDKs Programming Guide
filter_criteria = \
my_ls_stub.factory.create('ns0:LookupServiceRegistrationFilter')
filter_criteria.serviceType = filter_service_type
filter_criteria.endpointType = filter_endpoint_type
filter_criteria.nodeId = node_id
Managed services are registered with the instance name of the vCenter Server instance where
they run. The instance name maps to a unique vCenter Server ID. The instance name of a vCenter
Server system is specified during installation and might be an FQDN or an IP address.
Prerequisites
Procedure
2 Find the matching node name of the vCenter Server instance and save the ID.
Results
Use the node ID of the vCenter Server instance to filter subsequent endpoint requests. You can
use the node ID in a function that retrieves the endpoint URL of a service on a vCenter Server
instance. For information about implementing such a function, see Retrieve Service Endpoints on
vCenter Server Instances.
VMware, Inc. 24
VMware vSphere Automation SDKs Programming Guide
This example uses the steps that are described in the Retrieve a vCenter Server ID by Using the
Lookup Service procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
getMgmtNodeId(String targetNodeName)
{
// 1 - List the vCenter Server instances.
List<LookupServiceRegistrationInfo> serviceInfos =
lookupServiceUrls(“com.vmware.cis”,
“vcenterserver”,
“vmomi”,
“com.vmware.vim”);
...
This example uses the steps that are described in the Retrieve a vCenter Server ID by Using the
Lookup Service procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
def get_mgmt_node_id(node_instance_name) :
VMware, Inc. 25
VMware vSphere Automation SDKs Programming Guide
Prerequisites
n Determine the node ID of the vCenter Server instance where the vSphere Automation service
runs.
n Implement a function that retrieves the endpoint URL of a service on a vCenter Server
instance.
Procedure
1 Invoke the function for retrieving the endpoint URL of a service on a vCenter Server instance
by passing filter strings that are specific to the vSphere Automation API endpoint.
This example uses the steps that are described in the Retrieve a vSphere Automation API
Endpoint on a vCenter Server Instance procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
VMware, Inc. 26
VMware vSphere Automation SDKs Programming Guide
List<LookupServiceRegistrationInfo> results =
lookupSingleServiceUrl(“com.vmware.cis”,
“cs.vapi”,
“vapi.json.https.public”,
“com.vmware.vapi.endpoint”,
targetNodeId);
...
This example uses the steps that are described in the Retrieve a vSphere Automation API
Endpoint on a vCenter Server Instance procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
service_infos = lookup_service_infos(prod='com.vmware.cis',
svc_type='cs.vapi',
proto='vapi.json.https.public',
ep_type='com.vmware.vapi.endpoint',
node_id=my_mgmt_node_id)
my_vapi_url = service_infos[0].serviceEndpoints[0].url
VMware, Inc. 27
Authentication Mechanisms
4
To perform operations in the vSphere environment, principals must authenticate to the vSphere
Automation services. You can use different authentication mechanisms to achieve this goal.
To authenticate to the vSphere Automation services, client applications and users must obtain a
session identifier. You can choose from several supported authentication mechanisms to obtain a
session identifier and access the vSphere Automation services in the virtual environment.
First, you must decide whether to authenticate to vCenter Server by using the default identity
provider, vCenter Single Sign-On, or leverage your enterprise configuration to an external
identity provider, such as Microsoft Active Directory Federation Services (AD FS) or Okta.
vCenter Server acts as the default identity provider, by using its built-in vCenter Single Sign-
On service to authenticate users and service accounts.
In vSphere 7.0 and later, you can delegate vSphere identity management to an
external identity provider and activate benefits such as increased security and multifactor
authentication. In this scenario, vCenter Single Sign-On is replaced by an external identity
provider, such as Microsoft Active Directory Federation Services (AD FS) or Okta, as the
entity that performs the authentication of applications and users.
Identity provider federation enhances the security and compliance of your applications and
provides access to flexible benefits such as multifactor authentication (MFA) and automatic
account synchronization.
For more information, see Identity Provider Federation for vCenter Server.
Authentication Mechanisms
You can choose between basic and token-based authentication for login to the vSphere
Automation API. VMware encourages you to use token-based authentication as it provides
more security and flexibility for your applications and users.
Basic Authentication
VMware, Inc. 28
VMware vSphere Automation SDKs Programming Guide
By default, principals can use basic authentication with their vCenter Single Sign-On
credentials to connect to the vSphere Automation endpoint . The vSphere Automation
endpoint checks whether the user name and password are present in vmdir. On success,
the system returns a session identifier valid for the vSphere Automation endpoint.
If your vCenter Server is federated to an external identity provider, you can use basic
authentication through the OAuth 2.0 Password grant type.
Note VMware encourages you to move away from basic authentication and use token-
based authentication instead, as it is more secure and provides you with more options.
Token-based Authentication
Starting with vSphere 7.0, you can use token-based authentication for your federated
vCenter Server through the OAuth 2.0 grant types.
For code examples of authentication with the various OAuth 2.0 grant types, see the
vsphere-automation-sdk-java VMware repository at GitHub.
n Authentication Terminolgy
Authentication Terminolgy
To use the vSphere programming features effectively, you must understand a set of specific
authentication terms and concepts.
VMware, Inc. 29
VMware vSphere Automation SDKs Programming Guide
Term Definition
Identity Source (Directory Service) Stores and manages principals. Principals consist of
a collection of attributes about a user or a service
account such as name, address, email, and group
membership. Examples: Microsoft Active Directory and
VMware Directory Service (vmdir).
System for Cross-domain Identity Management (SCIM) The standard for automating the exchange of user
identity information between identity domains or IT
systems.
VMware Identity Services Starting in version 8.0 Update 1, VMware Identity Services
is a built-in container within vCenter Server that you can
use for identity federation to external identity providers. It
serves as an independent identity broker within vCenter
Server and comes with its own set of APIs. Currently,
Okta is the only external identity provider supported by
VMware Identity Services.
VMware, Inc. 30
VMware vSphere Automation SDKs Programming Guide
Term Definition
JSON Web Token (JWT) A token format defined by the OAuth 2.0 specification.
A JWT token carries authentication and authorization
information about a principal.
You connect to the vSphere Automation endpoint by using a user name and password known
to the vCenter Single Sign-On service. The vSphere Automation uses your credentials to
authenticate with the vCenter Single Sign-On Service and obtain a SAML token.
Prerequisites
n Retrieve the vSphere Automation endpoint URL from the Lookup Service.
n Verify that you have valid user credentials for the vCenter Single Sign-On identity store.
Procedure
1 Create a connection stub by specifying the vSphere Automation endpoint URL and the
message protocol to be used for the connection.
2 Create a stub configuration instance and set the specific security context to be used.
The security context object uses the user name and password that are used for
authenticating to the vCenter Single Sign-On service.
4 Call the create operation on the Session stub to create an authenticated session to the
vSphere Automation endpoint.
6 Update the stub configuration instance with the session security context.
VMware, Inc. 31
VMware vSphere Automation SDKs Programming Guide
What to do next
You can use the authenticated session to access vSphere Automation services. For more
information about creating stubs to the vSphere Automation services, see Chapter 5 Accessing
vSphere Automation Services.
This example uses the steps that are described in the Create a vSphere Automation Session with
User Credentials procedure
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
/*
* Create a stub for the session service using the authenticated
* session
*/
this.sessionSvc =
this.stubFactory.createStub(Session.class, stubConfig);
VMware, Inc. 32
VMware vSphere Automation SDKs Programming Guide
import requests
from com.vmware.cis_client import Session
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.session import create_session_security_context
from vmware.vapi.security.user_password import create_user_password_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
VMware, Inc. 33
VMware vSphere Automation SDKs Programming Guide
Client applications use the vCenter Single Sign-On service to retrieve SAML tokens. For more
information about how to acquire a SAML security token, see the vCenter Single Sign-On
Programming Guide documentation.
Prerequisites
Verify that you have the vCenter Single Sign-On URL. You can use the Lookup Service on
vCenter Server to obtain the endpoint URL. For information about retrieving service endpoints,
see Chapter 3 Retrieving Service Endpoints.
Procedure
1 Create a connection object to communicate with the vCenter Single Sign-On service.
Pass the vCenter Single Sign-On endpoint URL, which you can get from the Lookup Service.
2 Issue a security token request by sending valid user credentials to the vCenter Single Sign-On
service on vCenter Server.
Results
What to do next
You can present the SAML token to the vSphere Automation API endpoint or other endpoints,
such as the vSphere Web Services endpoint. The endpoint returns a session ID and establishes a
persistent session with that endpoint. Each endpoint that you connect to uses your SAML token
to create its own session.
This example uses the steps that are described in the Retrieve a SAML Token procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
VMware, Inc. 34
VMware vSphere Automation SDKs Programming Guide
This example uses the steps that are described in the Retrieve a SAML Token procedure.
n my_vapi_hostname
n my_sso_username
n my_sso_password
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
Prerequisites
n Retrieve the vSphere Automation endpoint URL from the Lookup Service.
VMware, Inc. 35
VMware vSphere Automation SDKs Programming Guide
Procedure
1 Create a connection by specifying the vSphere Automation API endpoint URL and the
message protocol to be used for the connection.
Note To transmit your requests securely, use https for the vSphere Automation API
endpoint URL.
2 Create the request options or stub configuration and set the security context to be used.
The security context object contains the SAML token retrieved from the vCenter Single
Sign-On service. Optionally, the security context might contain the private key of the client
application.
3 Create an interface stub or a REST path that uses the stub configuration instance.
The interface stub corresponds to the interface containing the method to be invoked.
The service creates an authenticated session and returns a session identification cookie to
the client.
6 Update the stub configuration instance with the session security context.
What to do next
Use the updated stub configuration with the session ID to create a stub for the interface that you
want to use. Method calls on the new stub use the session ID to authenticate.
This example uses the steps that are described in the Create a vSphere Automation Session with
a SAML Token
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
VMware, Inc. 36
VMware vSphere Automation SDKs Programming Guide
new StubConfiguration(samlSecurityContext);
/*
* Create a stub for the session service using the authenticated
* session
*/
this.sessionSvc =
this.stubFactory.createStub(Session.class, stubConfig);
This example uses the steps that are described in the Create a vSphere Automation Session with
a SAML Token
n my_vapi_hostname
n my_stub_config
n saml_token
The example assumes that you previously obtained a vSphere Automation API URL from the
Lookup Service, and a SAML token from the vCenter Single Sign-On Service.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
VMware, Inc. 37
VMware vSphere Automation SDKs Programming Guide
The vSphere Web Services API also supports session-based access. To establish an
authenticated session, you can send the SAML token retrieved from the vCenter Single Sign-On
service to a vSphere Web Service. In return, you receive a session identifier that you can use to
access the service. For more information about accessing Web Services and additional examples,
see the vSphere Web Services SDK Programming Guide documentation.
The vSphere Automation SDK for Python supports a simplified way of creating connections to
the Web Services API by using the pyVim library.
Prerequisites
n Retrieve the vSphere Web Services endpoint URL from the Lookup Service.
Procedure
2 Send the SAML token to a specific Web service to create an authenticated session.
VMware, Inc. 38
VMware vSphere Automation SDKs Programming Guide
The Service Content object gives you access to several server-side managed objects that
represent vSphere services and components.
This example uses the steps that are described in the Create a Web Services Session procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
... // Log in to the vSphere Web Services endpoint and retrieve a session
identifier. SamlTokenElement tokenElement = ssoConnection.getSamlBearerTokenElement(); String
sessionId = LoginByTokenSample.LoginUsingSAMLToken(tokenElement, vimUrl, null, null); //
Use the VimPortType and VimService objects from // the vSphere Web Services API for
accessing Web Services and // retrieve the request context. VimService vimService =
new VimService(); vimPortType vimPort = vimService.getVimPort(); // Add the retrieved
session ID to the request context. Map<String, Object> ctxt = ((BindingProvider)
vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vimUrl);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); Map<String, List<String>> headers
= (Map<String, List<String>>) ctxt.getMessageContext.HTTP_REQUEST_HEADERS); if (headers
== null) { headers = new HashMap<String, List<String>>(); } headers.put(“Cookie”,
Arrays.asList(vcSessionId); ctxt.put(MessageContext.HTTP_REQUEST_HEADERS, headers); // Use
the session ID context when retrieving the ServiceContent object. // The ServiceContent
object gives you access to a number of // server-side managed objects that represent vSphere
services and components. // For more information about the vSphere Web Services, // see the
vSphere Web Services SDK Programming Guide documentation.
ServiceContent serviceContent = VimUtil.getServiceContent(vimPort);
This example uses the steps that are described in the Create a Web Services Session procedure.
n my_ws_url
n my_sso_username
n my_sso_password
VMware, Inc. 39
VMware vSphere Automation SDKs Programming Guide
The my_ws_url variable represents the URL of the vCenter Server Web Services API endpoint.
You can retrieve the endpoint URL from the Lookup Service.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
With identity federation, you can use the same identity source for your vCenter Server that you
use for your other federated desktop and cloud applications.
VMware, Inc. 40
VMware vSphere Automation SDKs Programming Guide
protected credentials such as user names and passwords. Identity provider federation also helps
your organization with compliance as various international standards already require MFA to
guarantee data security. In addition, with identity provider federation, you can automate vCenter
Server user management because you utilize the users and groups from your main enterprise
identity source, for example Microsoft Active Directory.
You can configure federation to AD FS with the help of the vSphere Automation API. For more
information, see Federate vCenter Server to Microsoft Active Directory Federation Services (AD
FS).
Important Configuring VMware Identity Services for Okta is not possible through the vSphere
Automation API. To federate vCenter Server to Okta, you must use the vSphere Client. For more
information, see Configure vCenter Server Identity Provider Federation for Okta in the
vSphere Authentication Guide.
VMware, Inc. 41
VMware vSphere Automation SDKs Programming Guide
Prerequisites
n An AD FS root CA certificate added to the Trusted Root Certificates Store (also called the
VMware Certificate Store).
n You have created a vCenter Server administrators group in AD FS that contains the users you
want to grant vCenter Server administrator privileges to.
For more information about configuring AD FS, see the Microsoft documentation.
n vCenter Server must be able to connect to the AD FS discovery endpoint, and the
authorization, token, logout, JWKS, and any other endpoints advertised in the discovery
endpoint metadata.
Procedure
Method Description
setClientSecret The secret shared between the client and the provider.
setClaimMap This parameter is required but not applicable to AD FS. Use an empty array [].
VMware, Inc. 42
VMware vSphere Automation SDKs Programming Guide
Method Description
setUserName The user name of a user in the domain who has a minimum of read-only access to base
Distinguished Name (DN) for users and groups.
setPassword The password of a user in the domain who has a minimum of read-only access to base DN for
users and groups.
setUsersBaseDn The base DN for users in the Active Directory environment connected to AD FS that you want
to be able to federate with vCenter Server.
setGroupsBaseDn The base DN for groups in the Active Directory environment connected to AD FS that you
want to be able to federate with vCenter Server.
setServerEndpoints Active directory server endpoints. At least one Active Directory server endpoint must be set.
Use the format ldap://<hostname>:<port> or ldaps://<hostname>:<port>. The port is
typically 389 for LDAP connections and 636 for LDAPS connections. For Active Directory
multi-domain controller deployments, the port is typically 3268 for LDAP and 3269 for LDAPS.
setCertChain The SSL certificate chain in base64 encoding. You can skip this parameter only if all the Active
Directory server endpoints use the LDAP (and not the LDAPS) protocol.
VMware, Inc. 43
VMware vSphere Automation SDKs Programming Guide
Method Description
setConfigTag The configuration type of the identity provider. The possible values are Oauth2
and Oidc. For AD FS federation, use Oidc.
setName The user-friendly name for the identity provider. You must use the exact string
Microsoft ADFS for proper configuration.
setUpnClaim The name of the claim in the AD FS JWT token that contains the user principal
name of the user that is logging in. You must use the same value that you used
when you set up the AD FS Application Group. The procedure from the article in
the prerequisites uses upn. If unset, the default value is acct.
setGroupsClaim The name of the claim in the AD FS JWT token that contains the group
membership of the user that is logging in. You must use the same value that
you used when you set up the AD FS Application Group. The procedure from
the article in the prerequisites uses group. If unset, the groups for the subject
consist of the groups in group_names and group_ids claims.
setIsDefault Set to true. Specifies whether the provider is the default provider. Setting to
true makes all other providers non-default.
If unset:
n In case it is the first created provider, it is set as the default provider.
n In case it is not the first created provider, it is not set as the default provider.
6 Configure vCenter Server permissions for Active Directory users or groups in your AD FS
environment.
Note In vSphere 8.0 and later, you cannot configure permissions through the vSphere
Automation API. Instead, you use either the vSphere Client or the vSphere Web Services API.
For more information, see the vSphere Authentication Guide or the vSphere Web Services
SDK Programming Guide.
VMware, Inc. 44
VMware vSphere Automation SDKs Programming Guide
7 (Optional) Copy the two redirect URIs from the Identity Provider Configuration page in the
vSphere Client and add them to your AD FS Application Group.
Note You must do this step to enable logging in to vCenter Server through AD FS by using
the vSphere Client.
Results
VMware, Inc. 45
Accessing vSphere Automation
Services 5
vSphere Automation SDK provides mechanisms for creating remote stubs to give clients access
to vSphere Automation services.
The sequence of tasks you must follow to create a remote stub starts with creating
a ProtocolFactory. You use the protocol factory object to create a ProtocolConnection.
Connection objects provide the basis for creating stub interfaces tovSphere Automation services.
When you establish a connection to the vSphere Automation endpoint, you can create a
StubFactory object and a StubConfiguration object. With these objects, you can create the
remote stub for the vSphere Automation service that you want to access.
The complete connection sequence also includes SSL truststore support and a temporary
StubConfiguration that you use for SAML token authentication and session creation.
SSL Handshake
VMware, Inc. 46
VMware vSphere Automation SDKs Programming Guide
The vSphere Automation SDK for Java includes an SSL utility sample
code that supports the creation of a truststore for the HTTP connection,
com.vmware.vcloud.suite.samples.common.SslUtil.
Note The vSphere Automation SDK for Java SSL utility creates an instance of the
Java security certificate class X509TrustManager. This instance declares an override client-
side method, checkServerTrusted, that accepts all HTTPS certificates. This method is
suitable only for development environments. For a production environment, do not use
the X509TrustManager override methods. Instead, set up a truststore for use by the default
X509TrustManager implementation.
Prerequisites
Establish a connection to the vSphere Automation endpoint URL. For more information about the
authentication mechanisms that you can use, see Chapter 4 Authentication Mechanisms.
Procedure
The vSphere Automation API clients use ApiProvider instances to invoke operations on
services running in the virtual environment. To invoke an operation, you must specify the
target service and operation, input parameters, and execution context.
4 Create a StubConfiguration instance and set the security context to be used for the service
stub.
VMware, Inc. 47
VMware vSphere Automation SDKs Programming Guide
5 Create the stub for the vSphere Automation service interface by calling the create method
of the StubFactory instance. Pass the service class and the StubConfiguration instance as
arguments.
This example shows the steps for creating an authenticated session to the vSphere Automation
endpoint and creating the service stub for the Content Library API provider.
This example uses the steps described in the Access a vSphere Automation Service procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
/*
* Create a stub for the session service using the authenticated
* session
*/
this.sessionSvc =
this.stubFactory.createStub(Session.class, stubConfig);
VMware, Inc. 48
VMware vSphere Automation SDKs Programming Guide
VMware, Inc. 49
ESXi Hosts
6
Use the vSphere Automation APIs to run general operations on the ESXi hosts in your vSphere
environment.
You can retrieve information about the hosts, create a standalone host, disconnect, and
reconnect an ESXi host to a vCenter Server system.
To filter the ESXi hosts on a vCenter Server instance and get only the ones you want, call the
list function and pass your criteria with a HostTypes.FilterSpec instance. Combine several filter
criteria by including one or more of the following parameters:
n Connection state of the host which can be one of the following: CONNECTED, DISCONNECTED, or
NOT_RESPONDING.
n Power state of the host which can be one of the following: POWERED_OFF, POWERED_ON, or
STANDBY.
VMware, Inc. 50
VMware vSphere Automation SDKs Programming Guide
Add a single ESXi host to a vCenter Server instance by calling the create function and passing
a com.vmware.vcenter.HostTypes.CreateSpec instance as parameter. When you create the host
specification, make sure that you set the IP address or the DNS resolvable host name and the
administrator credentials.
When you add a host to a vCenter Server instance, the host is connected to vCenter Server
and becomes a managed host. To disconnect a managed host from a vCenter Server instance,
call the disconnect function and pass the host identifier as a parameter. The managed host
and its associated virtual machines remain in the inventory but vCenter Server temporarily stops
managing and monitoring them.
To reconnect a managed host to a vCenter Server instance, call the connect function and pass
the host identifier as a parameter. As a result, the connection status of the host changes, and
vCenter Server resumes managing the host and its associated virtual machines.
If you want to delete a host and all its associated virtual machines from the inventory, you can
remove the host from the vCenter Server instance. To delete a disconnected host from a vCenter
Server instance, call the delete function and pass the host identifier as a parameter.
VMware, Inc. 51
VMware vSphere Automation SDKs Programming Guide
You can configure the ESXi entropy sources by using the VMkernel boot options. To use
external entropy sources, set the entropySources value to more than or equal to 8. For more
information about how to set the desired entropy sources by using the VMkernel boot options,
see Controlling ESXi Entropy in the vSphere Security documentation.
You can also configure external entropy sources in the kickstart file for the ESXi scripted
installation. See Configuring External Entropy Sources During Scripted Installation.
Note If a host is configured to use only external entropy sources, that is, entropySources is set
to 8, you must keep supplying the external entropy data through the vSphere Automation API. In
case the entropy in the host gets exhausted, the host becomes unresponsive and might require a
hard reboot or re-installation to recover the host from this situation.
You can check whether an external entropy source is added to a host by calling the
get(host_id) method of the com.vmware.vcenter.host.entropy.ExternalPool interface and
passing the host ID as parameter. The method returns an ExternalPool.Info instance that
contains detailed information about the external entropy data on the host.
VMware, Inc. 52
VMware vSphere Automation SDKs Programming Guide
Table 6-1. Details for the External Entropy Data on a Host (continued)
When the external entropy data reaches the host, the entropy daemon stores it first in the in-
memory cache and the storage cache. Then the external entropy data is pushed to the VMkernel
entropy pool from which it is fed to the applications in need.
The entropy data in the storage cache persists on the host disk and is only consumed during
the ESXi booting. The default storage file size is 4MiB and can be configured through the ESXCLI
commands. See the ESXCLI Command Reference documentation.
VMware, Inc. 53
Managing the Life Cycle of Hosts
and Clusters 7
You can manage the life cycle of ESXi hosts collectively by using the vSphere Lifecycle Manager
feature through the vSphere Automation API. Starting with vSphere 8.0, you can manage the
lifecycle of a standalone ESXi host by using an image only through the vSphere Lifecycle
Manager automation API.
You can automate the life cycle management of a cluster or standalone host by performing the
following operations:
n Retrieve information about the current state of the cluster or the standalone host.
n Create a desired state that includes a specific version of the ESXi host. You can also add
some compatible partner software and firmware components and add-ons.
n Validate the desired state to detect any discrepancies between the desired state and the
host hardware.
n Check the compliance of a cluster or host against the desired state and determine whether
some additional steps must be taken to ensure the success of the cluster or host remediation.
You can use the vSphere Lifecycle Manager to manage the life cycle of hosts in a cluster that
meet the following requirements:
n All hosts in the cluster must be from the same vendor and with identical hardware.
n The hosts must include only integrated solutions, such as VMware vSAN™, vSphere with
®
Tanzu, NSX and VMware vSphere High Availability.
A standalone host is a host that is added to a vCenter Server instance but is not part of any
cluster. For more information about how to add, connect, and disconnect standalone host, see
Chapter 6 ESXi Hosts. You can manage the life cycle of a standalone host by performing almost
all vSphere Lifecycle Manager operations that you can perform on a cluster level. The only
limitation for managing the life cycle of a standalone host through the vSphere Automation API, is
that you can't update the firmware of the host.
VMware, Inc. 54
VMware vSphere Automation SDKs Programming Guide
n Software Depots
Term Definition
Upgrade, update, and patch You can upgrade to another major version of the software running on an ESXi
host, and install patches and updates that include smaller changes, bug fixes, or
other small improvements.
Depot A depot is a well-defined folder structure that is used for distributing payloads
and their metadata. Depots are consumed by different products and features
such as the vSphere Lifecycle Manager and ESXCLI. The vSphere Lifecycle
Manager works with three types of depots: online, offline, and UMDS. See
Software Depots.
Component A component is the smallest unit that the vSphere Lifecycle Manager uses during
the installation and update processes. Software vendors use components to
encapsulate a group of payloads that can be managed together.
Base image A base image is a collection of components that shape the bootable ESXi used
for the installation or upgrade process. Base images are currently distributed only
by VMware and support x86 servers. VMware provides new versions of the base
image for each upgrade, update, and patch release of the ESXi.
Base images are hosted at the VMware online depot that is available by
default to the vSphere Lifecycle Manager. Furthermore, you can download a
different base image version, in the form of an offline ZIP bundle, from https://
my.vmware.com/web/vmware/downloads.
VMware, Inc. 55
VMware vSphere Automation SDKs Programming Guide
Term Definition
Vendor add-on An add-on is a collection of components that different OEMs provide on top
of a base image. Vendors use an add-on to group some customizations for a
family of servers. Unlike base images, add-ons are not complete and are not
sufficient to boot an ESXi. Each add-on must have a unique name and version. An
add-on allows vendors to add, remove, or update components that are part of
the VMware base image, if there are no unresolved dependencies and conflicts
between the components.
Solution A solution contains one or more components, and provides information about its
constraints and compatibility with the different ESXi versions. For example, from
the perspective of the vSphere Lifecycle Manager solutions are VMware NSX,
®
VMware vSphere High Availability, vSAN.
Desired state A desired state of a cluster is represented with a software specification. The
desired state defines a set of components that a user wants to install on a single
ESXi host or on a cluster of hosts.
IOVP I/O Vendor Partner. Qualified VMware partners providing certified I/O device
drivers for network and storage host bus adapters.
Third-party software providers Providers of I/O filters, device drivers, CIM modules, and so on, that are not part of
VMware partner programs.
vSphere Configuration Profiles With vSphere Configuration Profiles, you can manage the configuration of all
hosts in a cluster collectively. This ensures consistency in host configuration at
a cluster level. You can enable vSphere Configuration Profiles only on clusters that
have the vSphere Lifecycle Manager enabled.
After you install vSphere 8.0 Update 1, you can access the feature through several major services
available on vCenter Server and on each ESXi host.
VMware, Inc. 56
VMware vSphere Automation SDKs Programming Guide
VMware
Store desired
vCenter state specifications Validate the desired
Component Server DB state and remediate
an ESXi Cluster
I/0 Vendor vCenter Server
Partner
ESXi Cluster
Add-on
OEM Image DB
Depot Manager Update
Partner
ESXi Image Manager
ESXi ≥7.0
Depot Manager
For each upgrade and patch release, VMware, OEMs, and other third-party companies make
the software updates of their products available to the customers. Software updates are
distributed to different locations and in different formats depending on the way they are
accessed, downloaded, and used. Depot Manager allows these different software resources to
be presented to the vSphere customers in a unified format and as a result, makes them easier to
use.
Depending on your environment and specific use case, Depot Manager gives you access to the
software updates within three different types of depots: online, offline, and UMDS. See Software
Depots.
Depot Manager that runs on the vCenter Server instance achieves the following goals:
n Caches the payloads and their metadata locally prior to their use.
n Enables depot overrides on a cluster or host level for Remote Office/Branch Office (ROBO)
environments, or Edge computing environments.
Depot Manager that runs on the hosts serves as a proxy to the vCenter Server Depot Manager. If
ROBO cluster or ROBO host, or Edge computing environments are enabled, Depot Manager that
runs on the ESXi hosts serves as a proxy to the nearby vSphere Lifecycle Manager compatible
depot.
VMware, Inc. 57
VMware vSphere Automation SDKs Programming Guide
Image Manager
Image Manager allows you to create a desired state that you can apply on a cluster or a
standalone host. The specification describes all components, add-ons, and the base image that
you can use to update or upgrade the hosts in your environment. Image Manager supports
validation of the desired state and the detecting drifts from the desired state.
The ESXi Updater Manager takes care of the actual remediation happening on each host.
To manage the life cycle of the hosts in your environment, you can use the vSphere Lifecycle
Manager through the vSphere Client. See Managing Host and Cluster Lifecycle.
This chapter of the vSphere Automation SDKs Programming Guide discusses how you can access
and use the functionality provided by the vSphere Lifecycle Manager Automation API.
n Depot management. You can add, remove, explore the contents of different types of depots.
See Software Depots. The content of the depots is provided by VMware and VMware
partners. Partners can use the ESXi Packaging Kit (EPK) to assemble a custom bootable
ESXi image. The custom image can then be shared to other third-party customers and used
through the Depot Manager service. For more information about how to create custom ESXi
images, see ESXi Packaging Kit (EPK) Development Guide.
n Desired software state. You can create, edit, and delete a desired software state for a cluster
or a standalone host on which the vSphere Lifecycle Manager is enabled. A desired software
state must contain at least a single ESXi image provided by VMware. You can also set an
add-on provided by OEMs, and one or more components by different software vendors.
Furthermore, during the process of creating the desired software state, you can check the
validity of the specification and compare the current state of the hosts in the cluster or the
standalone host with the desired software state.
VMware, Inc. 58
VMware vSphere Automation SDKs Programming Guide
n Cluster remediation. You can apply the desired state on each of the hosts in a cluster which
current state is different from the desired specification. Applying a desired state on a cluster
level has the following prerequisites:
n All hosts in the cluster must store their data on a local or remote disk, or on a USB drive.
n All hosts must contain only components that the vSphere Lifecycle Manager can
recognize and maintain. If a host contains some old content that the vSphere Lifecycle
Manager does not recognize, the content is removed from the host during remediation.
n Standalone host remediation. You can apply the desired software state on a standalone host
that is managed with baselines or on a standalone host that is managed with images but its
current state differs from the desired state.
Software Depots
A software depot represents a well-defined file structure used for storing and hosting the
ESXi software updates, patches, and upgrades that VMware, partners, and third-party vendors
provide. You can use the vSphere Automation APIs to manage the life cycle of the hosts in your
environment by applying software updates hosted on different depots.
Software depots are managed by the Depot Manager which is part of the vSphere Lifecycle
Manager. Software depots contain the actual payloads and the metadata of the software
updates. Depending on the way you access the software updates, the Depot Manager
recognizes three types of software depots: online, offline, and UMDS.
The following section of the documentation explains the concept of a software depot in terms of
the vSphere Lifecycle Manager feature. You can also find common use cases available through
the APIs for working with the different types of depots and their content.
Regardless of the different way in which you access each type of software depot, all depots
have the same structure. The same depot structure allows content from different vendors to be
uploaded to one depot. By default, you can access the content of the VMware online depot
at https://hostupdate.vmware.com/software/VUM/PRODUCTION/.... Furthermore, partners
and third-party customers can use the ESXi Packaging Kit to build and distribute software
updates in the form of offline or online depots. You can access their content by adding the
online vendor depot to the vSphere Lifecycle Manager or by downloading the content of the
offline depot to the vCenter Server instance.
VMware, Inc. 59
VMware vSphere Automation SDKs Programming Guide
Depot Manager
UMDS Depot
Download depot
metadata and
payloads
Add-on
Online Depot
VMware and partners upload software updates to the VMware online depot at https://
hostupdate.vmware.com/software/VUM/PRODUCTION/... or to a custom online depot.
Software updates can be patches of the ESXi base image, different versions of the partner add-
ons, the IOVP drivers certified by VMware, and the VMware Tools™ updates. Online depots are
accessible through a URL. By default, you can see the base images, add-ons, and components
provided within the VMware online depot at the following locations:
n https://hostupdate.vmware.com/software/VUM/PRODUCTION/main/vmw-depot-
index.xml
n https://hostupdate.vmware.com/software/VUM/PRODUCTION/addon-main/vmw-
depot-index.xml
n https://hostupdate.vmware.com/software/VUM/PRODUCTION/iovp-main/vmw-depot-
index.xml
n https://hostupdate.vmware.com/software/VUM/PRODUCTION/vmtools-main/vmw-
depot-index.xml
VMware, Inc. 60
VMware vSphere Automation SDKs Programming Guide
When you deploy the vCenter Server, the vSphere Lifecycle Manager is configured to access the
VMware online depot, by default. You can use the vSphere Automation APIs to add a custom
online depot to be managed by Depot Manager. The metadata of the newly added online depot
is not synchronized immediately. To synchronize the metadata, you can run a synchronization
operation or wait for the scheduled synchronization to take place.
The Depot Manager stores in the vCenter Server database only the metadata of the software
updates and the location of the added online depots. You can create a schedule to synchronize
the software updates metadata stored in the vCenter Server with the metadata available in the
accessible depots. The payloads of the software updates are downloaded only during the cluster
remediation process.
To add, remove, list, and retrieve information about the online depots, you can use the
com.vmware.esx.settings.depots.Online interface. See Working with Online Depots.
Offline Depot
The offline depot is also called an offline bundle and is distributed as a downloadable ZIP file.
Offline depots contain both the metadata and the payloads of the software update. Partners
and third-party customers can use the ESXi Packaging Kit to build and distribute offline bundles.
You can download offline bundles from the VMware website or from the websites of third-party
vendors. When you add an offline depot to the vSphere Lifecycle Manager depot, the software
updates are downloaded to the vCenter Server database.
UMDS Depot
In case, the vCenter Server instance is in an air-gapped environment and has no access to
any wire or wireless network, you can use a UMDS depot. The Update Manager Download
Service (UMDS) is available as a VMware-UMDS-8.0.1.-build_number.tar.gz file within the
ISO image of the vCenter Server appliance 8.0 UMDS is a 64-bit application and requires a 64-bit
Linux-based system. Install UMDS on a machine that has Internet access and is different from the
machine on which the vSphere Lifecycle Manager is running. For further information about how
to install and configure the UMDS module, see the Managing Host and Cluster Lifecycle.
You can set up a synchronization schedule for downloading specific software updates from
online vendor depots to the UMDS depot. Then use these updates to create desired software
state for the clusters in your environment.
To manage UMDS depots through the vSphere Automation API, you can use the
com.vmware.esx.settings.depots.Umds interface.
VMware, Inc. 61
VMware vSphere Automation SDKs Programming Guide
Use online depots to add new content over time to the management scope of the Depot
Manager. The Depot Manager periodically updates the software depots metadata stored on the
vCenter Server instance. In case new software updates are uploaded to the online depots, the
Depot Manager makes sure that the metadata stored on the vCenter Server database is updated
accordingly.
To add an online depot to the Depot Manager, you must first create the online
depot specification by using the com.vmware.esx.settings.depots.OnlineTypes.CreateSpec
class. To specify the URI to the vendor-index.xml file of the online depot, use the
setLocation(location) method of the OnlineTypes.CreateSpec class. Optionally, you can add
a description and enable the depot. By default, when you add an online depot to the Depot
Manager, the depot is enabled and its metadata is synchronized following the defined schedule.
If you want to synchronize the added online depot immediately, call the sync_Task() method of
the com.vmware.esx.settings.Depots interface. When you complete the depot specification, call
the create(spec) method of the com.vmware.esx.settings.depots.Online interface to add the
depot.
You can edit the depot description and disable the depot by creating an
com.vmware.esx.settings.depots.OnlineTypes.UpdateSpec object and pass it to the
update( depot, update_spec) method of the com.vmware.esx.settings.depots.Online interface.
You can remove an online depot from the list of currently configured depots by using
the delete(depotID) method of the com.vmware.esx.settings.depots.Online interface. The
invocation of this method does not remove the already downloaded metadata and payloads
from the deleted depot. You cannot delete the default VMware online depot, you can only
disable it.
To retrieve a list of currently configured online depots, call the list() method of the Online
interface. You can also retrieve information about a currently configured online depot by using
the get(depotID) method of the Online interface.
After you install and configure the Update Manager Download Service (UMDS) on a physical
machine with Internet access, you can add the UMDS depot to Depot Manager. Only one UMDS
depot can be added at a time to Depot Manager. When you add a UMDS depot, its content is not
immediately synchronized. To synchronize the content of the UMDS depots, you must call the
sync_Task() method of the com.vmware.esx.settings.Depots interface or wait for the scheduled
synchronization to take place.
VMware, Inc. 62
VMware vSphere Automation SDKs Programming Guide
You can always edit the initial UMDS depot settings, by calling the update(update_spec) method
of the Umds interface and passing an com.vmware.esx.settings.depots.UmdsTypes.UpdateSpec
object.
To retrieve information about the currently configured UMDS depot, use the get() method
of the Umds interface. You can remove a currently configured UMDS depot and all its
downloaded content from Depot Manager by calling the delete_Task() method of the
com.vmware.esx.settings.depots.Umds interface.
The Depot Manager does not synchronize immediately the metadata of the newly
added online and UMDS depots. If you want to force the synchronization and not wait
for the scheduled synchronization to take place, call the sync_Task() method of the
com.vmware.esx.settings.Depots interface. You can also define a custom schedule to sync the
metadata from the currently configured online or UMDS depots.
The default schedule is set to update the metadata daily at a random time. To reset the schedule
to the default settings, call the set(spec) of the SyncSchedule interface and pass null as an
argument.
VMware, Inc. 63
VMware vSphere Automation SDKs Programming Guide
To remediate a ROBO cluster, you must have access to a local software depot that hosts
the components of the desired state. You can use Depot Manager to either export the whole
vSphere Lifecycle Manager depot to an offline bundle, or export only the content of the desired
state required for remediating the ROBO cluster.
VMware, Inc. 64
VMware vSphere Automation SDKs Programming Guide
To export the desired state image from the vSphere Lifecycle Manager depot, call the
export(cluster,export_spec) method of the com.vmware.esx.settings.clusters.Software
interface. The method returns the URI of the offline bundle that is hosted on the vSphere
Lifecycle Manager Jetty Web server. To move the content of the offline bundle to the ROBO
location, you must physically copy the ZIP file, unarchive, and mount its content to an HTTP
server inside the ROBO environment.
To redirect a ROBO cluster to download software updates from a local repository and not
from the vSphere Lifecycle Manager depot on the vCenter Server instance, the vSphere
Automation API offer the cluster DepotOverrides service. To add a depot override location to
a ROBO cluster, call the add(cluster,override_depot) method of the DepotOverrides interface.
Specify the URI location of the local depot with the setLocation(location) method of the
com.vmware.esx.settings.clusters.DepotOverridesTypes.Depot class. During the ROBO cluster
remediation, Depot Manager instructs the hosts in the ROBO cluster to download the software
updates from the configured local depots within the ROBO cluster.
To retrieve a list of the base images available on a vCenter Server instance, call
the list(filter_spec) method of the com.vmware.esx.settings.depot_content.BaseImages
interface. To narrow the list of returned base images and retrieve only items matching to specific
criteria, you must pass a com.vmware.esx.settings.depot_content.BaseImagesTypes.FilterSpec
instance as an argument to the list method. Use the retrieved list to get some information about
each base image, including their display name and version, release date, and their category. You
can also get some detailed information about a single base image by using the get(version)
method of the com.vmware.esx.settings.depot_content.base_images.Versions interface. The
information includes a list of the components present in this base image.
To retrieve a list of all currently available add-ons in the vSphere Lifecycle Manager depot, call
the list(filter_spec) method of the com.vmware.esx.settings.depot_content.AddOns interface
and pass null as an argument. You can filter the available add-ons by using some specific criteria
such as the add-on vendor, name, versions, or minimum version. You can retrieve some detailed
information about a single add-on version, by calling the get(name,version) method of the
com.vmware.esx.settings.depot_content.add_ons.Versions interface. The information includes
the list of components part of the add-on, and the list of components that were removed by this
add-on version.
VMware, Inc. 65
VMware vSphere Automation SDKs Programming Guide
Starting with vSphere 8.0 Update 1, you can use the Virtual Infrastructure Management API
which introduced a new way of accessing and using the vSphere Web Services. That is, you can
now use the JSON data format over HTTP and create REST-like requests to the vSphere Web
Services. Use the Virtual Infrastructure API or the vSphere Web Services API to create a cluster.
For more information about how to authenticate and use the Virtual Infrastructure Management
API, see the vSphere Web Services SDK Programming Guide.
You can call the Folder.CreateClusterEx(createClusterEx) method and pass as arguments the
name for the new cluster and a ClusterConfigSpecEx data object. In the data object, among
other properties, you can specify the desired state for the cluster. The desiredSoftwareSpec
property in the ComputeResourceConfigSpec data object contains the desired software
specification for the cluster. This property is available for applications using the vSphere Web
Services API of version 7.0 and later. You can create a DesiredSoftwareSpec data object and
specify the base image that must be applied on the cluster with the baseImageSpec property.
Optionally, you can specify a vendor add-on to be added to the software specification with the
vendorAddOnSpec property.
Starting with vSphere 8.0, you can also enable the cluster to use vSphere Configuration Profiles
by setting the enableConfigManager property of the ComputeResourceConfigSpec data object to
true.
VMware, Inc. 66
VMware vSphere Automation SDKs Programming Guide
Before you enable vSphere Lifecycle Manager on a cluster, you can check whether the cluster
meets all prerequisites. vSphere Lifecycle Manager can be enabled for a cluster only if the
following requirements are met:
n All hosts in the cluster include only components that belong to integrated solutions, such as
®
VMware vSAN™ and VMware vSphere High Availability.
n None of the hosts in the cluster are in the process of active remediation through the VMware
®
vSphere Update Manager™.
The cluster ID represents the unique identifier for a cluster resource. To retrieve
commonly used information about clusters including their IDs, call the list(filter_spec)
method of the com.vmware.vcenter.Cluster interface and pass as argument a
com.vmware.vcenter.ClusterTypes.FilterSpec instance to list the clusters that match specific
criteria. You receive a list of com.vmware.vcenter.ClusterTypes.Summary objects which you can
use to get the cluster ID.
You pass a CkeckSpec instance to specify which checks can be skipped during the cluster
preliminary check. Though you can skip some checks with this operation, the Image Manager
runs all checks during the enablement operation. If you leave the check specification empty, all
checks are run for each host in the cluster. You can select among the following checks to be
skipped when running a pre-check operation:
n SOFTWARE. Checks whether there are any orphaned vSphere Installation Bundles (VIBs) and
any software that cannot co-exist with vSphere Lifecycle Manager.
n VERSION. Checks whether all hosts in the cluster are of version greater than a predefined one.
n STATELESSNESS. Checks whether there are any stateless hosts in the cluster. vSphere Lifecycle
Manager can be enabled only if the cluster does not contain stateless hosts.
n VUM_REMEDIATION. Checks whether any of the hosts in the cluster are currently remediated
®
through the VMware vSphere Update Manager™.
VMware, Inc. 67
VMware vSphere Automation SDKs Programming Guide
You can also get information about which clusters in your environment are managed with a single
software specification. Call the get(cluster_ID) method and pass the cluster ID as an argument.
You can add a standalone host to a vCenter Server instance under a data center object or into
a folder. See Chapter 6 ESXi Hosts. If you remove a host from a cluster but leave it in the data
center, the host is also considered a standalone host.
To manage a standalone host with a software specification, you must first enable
the vSphere Lifecycle Manager on that host. You can run a preliminary check
to establish whether the standalone host meets all requirements for enabling the
vSphere Lifecycle Manager. Call the check_Task(host_ID, check_spec) method of the
com.vmware.esx.settings.hosts.enablement.Software interface and pass as arguments the host
identifier and a CheckSpec instance. The pre-checks that you can skip before enabling the
vSphere Lifecycle Manager on a standalone host are the same as for a cluster.
VMware, Inc. 68
VMware vSphere Automation SDKs Programming Guide
The draft software specification is the working copy of the desired software state. Only one user
at a time is allowed to edit a single draft for a cluster or a standalone host. Before saving the
changes to the edited draft version, you can validate the content of the draft.
A typical workflow for working with draft software specifications starts with creating a draft
software specification for a specific cluster or a standalone host. If the cluster or the standalone
host already have a software specification defined, this action takes the latest committed draft
and you can edit its contents according to your needs. If the cluster or the standalone host have
no software specification created yet, this method creates an empty draft. The only mandatory
item for a draft is a base image of a specific version.
After you complete adding components, an add-on, and a base image, you can save your
changes by committing the draft. This operation results in setting the committed draft as the
current desired state of the cluster or the standalone host. Before committing the draft software
specification, you can validate the contents of the draft or check whether all hosts in the cluster
or the single standalone host are compliant with the draft.
If the commit operation is successful, the draft becomes the desired state for the cluster or the
standalone host. You can now export the software specification and use it, for example, in a
ROBO cluster scenario or another standalone host. You can also validate the compliance of the
hosts in the cluster or the standalone host against the desired state and then apply the software
specification, if feasible.
VMware, Inc. 69
VMware vSphere Automation SDKs Programming Guide
Pass the cluster ID or the host ID as an argument to the respective method. As a result, you
receive a draft ID which you can use to add a base image, an add-on, or some components to
the draft.
n For a standalone host, call the set(host_ID, draft_ID, base_image_spec) method of the
com.vmware.esx.settings.hosts.software.drafts.software.BaseImage interface and pass
as arguments the standalone host and draft ID, and a base image specification.
If the draft contains a base image, this method overwrites the existing image. The base
image specification contains the version of the bootable ESXi that must be included in
the desired state. To retrieve details about the base image that is currently present in
a draft, call the get(cluster_ID,draft_ID) or get(host_ID, draft_ID) methods of the
com.vmware.esx.settings.clusters.software.drafts.software.BaseImage interface. Pass as
arguments the cluster or the standalone host ID and the draft ID. Use the returned
com.vmware.esx.settings.BaseImageInfo object to query the version, display name and version,
and the release date of the ESXi host.
Pass as arguments to these methods the cluster or the standalone host ID, the draft ID,
and the add-on specification. If you want to remove an add-on from a draft, call the
delete(cluster_ID,draft_ID) or delete(host_ID,draft_ID) method of the respective AddOn
interface and pass as arguments the cluster or the standalone host ID, and the draft ID.
You can add a component, change the version, or delete an existing component from a draft
software specification. To change the version of a component included in a draft:
VMware, Inc. 70
VMware vSphere Automation SDKs Programming Guide
n For a standalone host, call the set(host_ID, draft_ID, component_ID, version) method of
the com.vmware.esx.settings.hosts.software.drafts.software.Components interface.
As a result, you add the component specified with the component_ID and version
arguments to the draft, if it is missing. To remove a component from a draft, call
the delete(cluster_ID,draft_ID,component_ID) or delete(host_ID,draft_ID,component_ID)
method of the respective Components interface. You can change multiple
components in a draft by calling the update(cluster_ID,draft_ID,update_spec) or
update(host_ID,draft_ID,update_spec) method of the respective Components interface. To
specify the components you want to remove, add, or update for a draft, pass a cluster or a
host ComponentsTypes.UpdateSpec instance as an argument to the update method.
To retrieve information about all components present in a draft, or a single component, you can
use the list methods of the respective Components interface.
The Drafts service offers two methods for validating the draft software specification.
To check whether a draft is complete and there are no conflicts between the draft
components, or unresolved dependencies, call the validate_Task(cluster_ID,draft_ID) or
validate_Task(host_ID,draft_ID) method of the respective Drafts interface. Pass as arguments
to the method the cluster or the standalone host ID, and the draft ID. You validate whether there
were any other drafts committed for this cluster or standalone host, which can make the current
commit operation invalid. The method also validates whether all components defined in the
software specification are available in the depot metadata. This method does not run compliance
checks against the cluster or the standalone host.
To check whether all hosts in the cluster or the standalone host are compliant
with the draft software specification, call the scan_Task(cluster_ID,draft_ID) or
scan_Task(host_ID,draft_ID) method of the respective Drafts interface. Pass as arguments to
this method the cluster or the standalone host ID, and the draft ID. This method results in running
a comparison between the draft specification and the current state of each host in the cluster or
the current state of the standalone host.
VMware, Inc. 71
VMware vSphere Automation SDKs Programming Guide
To save the draft that you created for a cluster or a standalone host, call the
commit_Task(cluster_ID,draft_ID,draft_commit_spec) or commit_Task(host_ID, draft_ID,
draft_commit_spec) method of the respective Drafts interface. The Image Manager component
runs a validation check before the draft gets saved to the database. This method returns an
identifier of the commit operation. You can use the ID to retrieve information about a specific
commit such as the author of the commit operation, the time when the draft was committed, and
so on.
You can export a software specification created for a cluster or a standalone host by using one
of the following formats:
n An ISO image.
n A JSON file.
Use the vSphere Lifecycle Manager API to import a software specification as a draft and then
edit it. You have several options for running the import operation depending on the location and
format of the desired software state.
VMware, Inc. 72
VMware vSphere Automation SDKs Programming Guide
This method does not export any information about the solutions available on the cluster or the
standalone host since the constraints set by these solutions might not be applicable for another
cluster or host. Pass as parameters the cluster or the standalone host ID, and an instance of the
respective SoftwareTypes.ExportSpec class.
n Export as an offline bundle in a ZIP file format. Call the getExportOfflineBundle() method of
the ExportSpec instance. You can use the exported offline bundle to create a depot and add
its components to the resources managed by the Depot Manager module.
n Export as a JSON file holding the desired state specification. Call the
setExportSoftwareSpec(exportSoftwareSpec) method of the ExportSpec instance and pass
true as argument. You can then reuse the JSON file to apply the desired state that it contains
to another cluster or standalone host in the same or in a different vCenter Server instance.
Note that the JSON file holds only the description of the desired state. You must check
whether all components described in the JSON file are available in the depot for the target
cluster. See Importing a Desired State Specification for information about how you can use a
desired state specification for another cluster or standalone host.
VMware, Inc. 73
VMware vSphere Automation SDKs Programming Guide
Pass as parameters the cluster or the standalone host ID, and an instance of the respective
DraftsTypes.ImportSpec class. Use the instance of the import specification to describe the
download source and the source type of the imported software specification. Depending on the
location and the source type of the exported desired state, you can choose from the following
import options:
n Import a file from the vCenter Server or your local file system. Call the setFileId(fileId)
method of the ImportSpec instance. Pass as argument the file ID of the software specification
which was previously uploaded on the Jetty Web server running on the vCenter Server
at https://<vcenter_FQDN>:9087/vum-fileupload URL. You can also use this option to
import a specification file that resides on your local file system. Make sure you set the source
type of the import specification to PUSH through the setSourceType(sourceType) method of
the ImportSpec instance.
n Import a file that resides on a URI location. Call the setLocation(location) method of the
ImportSpec instance. Pass as argument the URI location of the software specification file. The
software specification can be pulled from a URI location with one of the following schemes:
file, http, or https. You can use this import mechanism only if you set the source type to
SourceType.PULL.
To check the compliance of all hosts in a cluster or of the single standalone host:
Pass as an parameter the cluster or the host identifier. The method compares the desired state
against the current state of each host in the cluster or of the single host and as a result calculates
the compliance.
VMware, Inc. 74
VMware vSphere Automation SDKs Programming Guide
You can retrieve the cluster or the standalone host compliance status by calling the
get(cluster_ID) or get(host_ID) method of the respective Compliance interface and
passing as argument the cluster or the standalone host ID. As a result you receive a
com.vmware.esx.settings.ClusterCompliance or a com.vmware.esx.settings.HostCompliance
object. You can use the ClusterCompliance or the HostCompliance instance to retrieve the
following information:
n The overall cluster compliance status regarding the target version of the components
described within the cluster desired state.
n The impact of applying the desired state on the cluster in case the cluster is non-compliant.
n A list of the unavailable hosts which cannot be checked for compliance against the desired
state.
n The ID of the committed draft for which the compliance check is performed. If the
getCommit() method of the ClusterCompliance or the HostCompliance instance returns null,
the compliance check is run against a draft software specification.
n The compliance overall stage status of the cluster or the standalone host and is relevant
when the compliance status of the cluster or the standalone host is NON_COMPLIANT.
n The compliance of the OEM add-on on the standalone host with respect to the add-on in the
desired state.
n The compliance of the base image on the standalone host with respect to the base image in
the desired state.
n The compliance of all effective components and all components present on the standalone
host in respect to the components in the desired state.
n The compliance of all DPU devices on the standalone host with respect to the desired state.
n The compliance of the hardware support on the standalone host with respect to the
hardware support defined in the target state.
A cluster or a standalone host can have one of the following compliance statuses regarding the
target versions:
n COMPLIANT. The target versions of the components described in the desired state of the
cluster or the standalone host are the same as the versions of the components currently
present on the hosts in the cluster or on the standalone host.
VMware, Inc. 75
VMware vSphere Automation SDKs Programming Guide
n NON_COMPLIANT. The desired state of the cluster or the standalone host describes components
with higher versions than the versions of the components currently present on the hosts in
the cluster or on the standalone host. Non-compliant clusters or hosts are those clusters or
hosts which have orphaned VIBs, or components on the hosts that are not present in the
desired state specification.
n INCOMPATIBLE. One or more hosts in the cluster or in the standalone host have components
with higher versions than the components described in the desired state specification.
n UNAVAILABLE. The current state of one or more hosts in the cluster or of the standalone host
cannot be retrieved and as a result the compliance check cannot be performed.
You can check the compliance impact of applying the desired state on a non-compliant
cluster or a standalone host by calling the getImpact() method of the ClusterCompliance or
the HostCompliance instance. A com.vmware.esx.settings.ComplianceImpact object is returned.
Use it to retrieve information about the steps you must take to remediate the cluster or the
standalone host successfully. You might need to reboot a host or put a host into maintenance
mode to remediate the cluster or the standalone host successfully.
To use services form the com.vmware.esx.hcl.hosts package, you must verify that you have
accepted to participate in the CEIP and there is available compatibility data.
VMware, Inc. 76
VMware vSphere Automation SDKs Programming Guide
When you run cluster and standalone host compliance checks, the Coordinator module runs a
series of checks on each host to determine their state and whether some additional actions must
be taken to ensure the success of the remediation operation. In case one or more hosts in the
cluster and any of the standalone hosts are evaluated as non-compliant, additional checks are
run on those hosts to evaluate whether they must be rebooted or put into maintenance mode.
Currently, VMware provides a set of behavior controls (remediation policies) regarding the virtual
machines and the hosts in a cluster or a standalone host. This set of remediation policies might
change with the next vSphere release.
VMware, Inc. 77
VMware vSphere Automation SDKs Programming Guide
All clusters and standalone hosts in a vCenter Server instance inherit the default or the
overridden global policy settings unless the global policy is explicitly overridden on a cluster
and host level.
To view the cluster- and host-specific remediation policies, call the get(cluster_ID) or
get(host_id) method of the respective com.vmware.esx.settings.clusters.policies.Apply
or com.vmware.esx.settings.hosts.policies.Apply interface. The method returns an instance
of the com.vmware.esx.settings.clusters.policies.ApplyTypes.ConfiguredPolicySpec or
com.vmware.esx.settings.hosts.policies.ApplyTypes.ConfiguredPolicySpec class which
contain the cluster- and host-specific policies to be applied during
VMware, Inc. 78
VMware vSphere Automation SDKs Programming Guide
Method Description
setDisableDpm(disableDpm) Deactivate the VMware Distributed Power Management (DPM) feature for all clusters or
for a specific cluster. DPM monitors the resource consumption of the virtual machines in
a cluster. If the total available resource capacity of the hosts in a cluster is exceeded,
DPM powers off (or recommends powering off) one or more hosts after migrating their
virtual machines. When resources are considered underutilized and capacity is needed,
DPM powers on (or recommends powering on) hosts. Virtual machines are migrated
back to these hosts.
During the cluster remediation, the vSphere Lifecycle Manager cannot wake up and
remediate hosts that are automatically put into a stand-by mode by DPM. These
hosts stay non-compliant when DPM turns them on. The vSphere Distributed Resource
Scheduler (DRS) is unable to migrate virtual machines to the hosts which are not
remediated with the desired state for the cluster.
To deactivate DPM during the cluster remediation, call the setDisableDpm(disableDpm)
method of the ConfiguredPolicySpec instance and pass as argument true. By default,
the vSphere Lifecycle Manager temporarily deactivates DPM and turns on the hosts to
complete the remediation. DPM is enabled again when the cluster remediation finishes.
setDisableHac(disableHac) Deactivate the vSphere HA admission control. vSphere HA uses admission control to
ensure that a cluster has sufficient resources to guarantee the virtual machines recovery
when a host fails. If vSphere HA admission control is enabled during remediation, putting
a cluster into maintenance mode fails because vMotion cannot migrate virtual machines
within the cluster for capacity reasons.
To allow the vSphere Lifecycle Manager to temporary deactivate vSphere HA admission
control, call the setDisableHac(disableHac) method of the ConfiguredPolicySpec
instance and pass as argument true. By default, the vSphere HA admission control is
enabled because DRS should be able to detect issues with the admission control and
deactivate it to allow the remediation to complete.
setEvacuateOfflineVms(evacu Migrate the suspended and powered off virtual machines from the hosts that must enter
ateOfflineVms) maintenance mode to other hosts in the cluster. To enable this remediation policy, call
the setEvacuateOfflineVms(evacuateOfflineVms) method of the ConfiguredPolicySpec
instance and pass as argument true. By default, this setting is deactivated in the global
remediation policy.
VMware, Inc. 79
VMware vSphere Automation SDKs Programming Guide
Method Description
setFailureAction(failureAct Specify what actions vSphere Lifecycle Manager must take if a host fails to
ion) enter maintenance mode during the remediation. To configure this policy on a
global or cluster-specific level, call the setFailureAction(failureAction) method of
the ConfiguredPolicySpec instance. Pass as argument an ApplyTypes.FailureAction
instance. You can set the number of times that vSphere Lifecycle Manager tries to put
a host into maintenance mode and the delay between the tries. When the threshold is
reached and the host failed to enter maintenance mode, the cluster remediation fails.
By default, vSphere Lifecycle Manager tries to put a host into maintenance mode three
times with a five minute delay between each try before the cluster remediation fails.
setEnforceHclValidation(enf Prevents the remediation of vSAN clusters if vSphere Lifecycle Manager reports
orceHclValidation) hardware compatibility issues during the hardware compatibility check performed as
part of the remediation pre-check or the remediation tasks of the cluster. If you pass
null as a parameter, detected hardware issues are reported as warnings and do not
prevent the remediation of the vSAN cluster.
setParallelRemediationActio Enable simultaneous remediation of all hosts that are in maintenance mode with in the
n(parallelRemediationAction cluster. Pass an instance of the
) com.vmware.esx.settings.defaults.clusters.policies.ApplyTypes.ParallelRemediat
ionAction class to indicate the maximum number of hosts that can be remediated in
parallel.
Note If the hosts have NSX virtual distributed switches that are ready to be migrated to
vSphere Distributed Switches, you must manually set the maximum number of parallel
remediations to no more than 4. In cases when host switch migration is needed, if more
than 4 hosts are remediated in parallel, the remediation might fail, because the host
switch migration takes more time than the time vSphere Lifecycle Manager needs to
complete the parallel remediation.
VMware, Inc. 80
VMware vSphere Automation SDKs Programming Guide
Method Description
setPreRemediationPowerActio Specify how the power state of the virtual machines must change before the host enters
n maintenance mode. If DRS is not enabled on a cluster or the automation level of a
(preRemediationPowerAction) DRS cluster is not set to fully automated, the Coordinator module fails to remediate the
cluster if the remediation requires a reboot or maintenance mode. You can set a policy
that powers off or suspends the virtual machines on hosts that must be rebooted or
must enter maintenance mode during remediation. The DRS takes care of changing the
power state of the virtual machines when the host enters and exits maintenance mode.
To set a policy for the power state of the virtual machines during the
remediation, call the setPreRemediationPowerAction(preRemediationPowerAction)
method of the ConfiguredPolicySpec instance. Pass as a parameter an instance of the
PreRemediationPowerAction enumeration class and specify one of the following values:
setEnableQuickBoot(enableQu Reduce the reboot time of an ESXi host by skipping all the hardware initialization
ickBoot) processes and restarting only the hypervisor. This policy is applicable only if the host
platform supports the Quick Boot feature.
To enable the Quick Boot feature on the hosts during the remediation, call the
setEnableQuickBoot(enableQuickBoot) method of the ConfiguredPolicySpec instance
and pass as argument true. By default, this policy is deactivated.
VMware, Inc. 81
VMware vSphere Automation SDKs Programming Guide
Method Description
setEnableQuickBoot(enableQu Optimize the host patching and upgrade operations by reducing the reboot time of an
ickBoot) ESXi host. Since the patching and upgrading operations do not affect the hardware of
the host, the hardware initialization processes can be skipped. This policy is applicable
only if the host platform supports the Quick Boot feature. For more information
about which hosts are Quick Boot compatible, see the following KB article https://
kb.vmware.com/s/article/52477.
setPreRemediationPowerActio Specify how the power state of the virtual machines must change before the standalone
n host enters maintenance mode. You can choose between the following power actions:
(preRemediationPowerAction) n DO_NOT_CHANGE_VMS_POWER_STATE. Indicates that the power state of the virtual
machines must not be changed.
n POWER_OFF_VMS. Indicates that the virtual machines must be powered off before the
standalone host enters maintenance mode.
n SUSPEND_VMS. Indicates that the virtual machines must be suspended before the
standalone host enters maintenance mode.
n SUSPEND_VMS_TO_MEMORY. Indicates that the virtual machines must be suspended
before the standalone host enters maintenance mode.
setFailureAction(failureAct Specify what actions vSphere Lifecycle Manager must take if a standalone host fails to
ion) enter maintenance mode during the remediation. You can set the number of times that
vSphere Lifecycle Manager tries to put a standalone host into maintenance mode and
the delay between the tries. When the threshold is reached and the standalone host
failed to enter maintenance mode, the host remediation fails.
VMware, Inc. 82
VMware vSphere Automation SDKs Programming Guide
third-party solutions on a cluster managed with images, you must integrate the solutions with
vSphere Lifecycle Manager.
Examples of VMware integrated solutions are VMware NSX®, vSAN, and vSphere with Tanzu. For
more information about the VMware integrated solutions, see vSphere Lifecycle Manager Images
and Other VMware Products and Solutions section in the Managing Host and Cluster Lifecycle
documentation.
Third-party software providers can use the vSphere APIs, VMware vSphere APIs for I/O Filtering
(VAIO), VMware Daemon Software Development Kit, and others to develop third-party solutions
for their vSphere platforms.
You can use the vSphere Lifecycle Manager automation APIs to manage the life cycle of third-
party solutions on a cluster managed with a single image. First you need to package and upload
your solution components to thevSphere Lifecycle Manager depot. Use the depot to store and
manage the software updates for your third-party solutions. To make a solution available on
a cluster, create a software specification that contains the solution and remediate all hosts in
the cluster with that image. vSphere Lifecycle Manager manages the life cycle of the solution
components by consuming the software updates from the vSphere Lifecycle Manager depot.
Note If you export an image from the cluster where your third-party solution is running, the
solution components are not part of the exported image.
Prerequisites
To enable vSphere Lifecycle Manager to manage your third-party solutions, you must use the
ESXi Packaging Kit (EPK) to create installable packages. As of the vSphere 7.0 release, partner
development kits generate components as installation packages. For more information about
how to use the EPK to create components, assemble components into add-ons, then merge the
add-ons with the base image to author a depot, see the ESXi Packaging Kit (EPK) Development
Guide documentation.
n The following example creates an online depot that can be accessed through the
http://my_online_depot.com URL.
POST https://<vcenter_server_ip_or_fqdn>/api/esx/settings/depots/online
{
"description" : "My online depot adds the My Solution component to the ESXi 7.0U3d
base image",
"ownerdata" : "ACME Company",
"location" : "http://my_online_depot.com",
"enabled" : true
}
VMware, Inc. 83
VMware vSphere Automation SDKs Programming Guide
n The following example creates an offline depot, also called an offline bundle, that can be
imported to the vSphere Lifecycle Manager depot.
POST https://{server}/api/esx/settings/depots/offline?vmw-task=true
{
"file_id" : "string",
"description" : "string",
"ownerdata" : "string",
"source_type" : "PULL",
"location" : "http://myurl.com"
}
2 Synchronize the online depot to download the depot metadata and make the vSphere
Lifecycle Manager aware of your solutions. See Synchronizing Software Depots.
POST https://<vcenter_server_ip_or_fqdn>/api/esx/settings/depots/online?vmw-
task=true&action=sync
POST https://<vcenter_server_ip_or_fqdn>/api/esx/settings/clusters/<cluster_id>/software/
drafts
4 Add your solution to the created draft software specification. See Editing a Draft Software
Specification.
PUT https://<vcenter_server_ip_or_fqdn>/api/esx/settings/clusters/<cluster_id>/software/
drafts/<draft_id>/software/components/<component_id>
5 Save the created draft software specification to make it the desired state for the cluster. See
Committing the Draft Software Specification.
POST https://<vcenter_server_ip_or_fqdn>/api/esx/settings/clusters/<cluster_id>/software/
drafts/<draft_id>?action=commit&vmw-task=true
6 Remediate the ESXi cluster with the desired state that contains your solution to apply the
desired state on all hosts in that cluster. See Remediating an ESXi Cluster and a Standalone
Host.
POST https://<vcenter_server_ip_or_fqdn>/api/esx/settings/clusters/<cluster_id>/software?
action=apply&vmw-task=true
{
"hosts" : [
"obj-103",
"obj-103"
],
"commit" : "obj-103",
"accept_eula" : true
}
VMware, Inc. 84
VMware vSphere Automation SDKs Programming Guide
Results
You set up an image for the cluster which includes your third-party solution. You now manage all
hosts in the cluster collectively with a single image. Upon remediation, the image is installed on all
hosts in the cluster.
What to do next
You can update, delete or add new solutions to the draft software specification and then commit
the changes to make the draft the desired state for the cluster.
VMware, Inc. 85
VMware vSphere Automation SDKs Programming Guide
VMware, Inc. 86
Virtual Machine Configuration and
Management 8
A virtual machine is a software computer that, like a physical computer, runs an operating system
and applications. The virtual machine consists of a set of specification and configuration files and
is backed by the physical resources of a host. Each virtual machine encapsulates a complete
computing environment and runs independently of the underlying hardware.
Starting with vSphere 6.5, you can create virtual machines, configure virtual machine settings,
and perform power operations on the virtual machines through the vSphere Automation APIs.
Starting with vSphere 7.0, you can use the vSphere Automation APIs to perform various virtual
machine management operations. For example, you can deploy virtual machines by using several
approaches, clone an existing virtual machine, create an instant clone of a running virtual
machine. You can also install VMware Tools which enables you to manage the life cycle and
customize the networking and identity settings of the guest operating system installed on the
virtual machine.
You can create a basic virtual machine and then configure it according to your needs. You can
also create a more comprehensive virtual machine and then edit its settings. To create a virtual
machine, you must specify the datastore, resource pool, folder, or host where the virtual machine
is placed. Later, you can customize the virtual machine by specifying the boot options, number of
CPUs, the guest OS, and virtual NIC. See Creating a Virtual Machine Without a Clone or Template
and Configuring Virtual Machines.
VMware, Inc. 87
VMware vSphere Automation SDKs Programming Guide
You can use a turned off virtual machine to create a VM template from which to deploy other
virtual machines. See Create a VM Template in a Content Library from a Virtual Machine. You can
also mark a virtual machine as template by calling the VirtualMachine.MarkAsTemplate method
from the vSphere Web Services APIs. See vSphere Web Services SDK Programming Guide.
You can capture a virtual machine or a vApp in an OVF template and store the template in a
content library. Then you can use the OVF template to deploy a virtual machine or a vApp in
your environment. See Creating Virtual Machines and vApps from Templates in a Content Library.
When you create a virtual machine without a template or clone, you can configure the virtual
hardware, including processors, hard disc, memory. To create a virtual machine, you must specify
the virtual machine attributes by using the CreateSpec class. For example, you can specify a
name, boot options, networking, and memory for the new virtual machine.
All attributes are optional except the virtual machine placement information that you must
provide by using the PlacementSpec class. Use the virtual machine placement specification to
set the datastore, cluster, folder, host, or resource pool of the created virtual machine. You must
make sure that all these vSphere objects are located in the same data center in a vCenter Server
instance.
For more information, refer to the API Reference documentation inside the SDK.
This example uses the information provided in Creating a Virtual Machine Without a Clone or
Template.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
VMware, Inc. 88
VMware vSphere Automation SDKs Programming Guide
DiskTypes.CreateSpec dataDiskCreateSpec =
new DiskTypes.CreateSpec.Builder().setNewVmdk(
new DiskTypes.VmdkCreateSpec()).build();
List<DiskTypes.CreateSpec> disks = Arrays.asList(bootDiskCreateSpec,
dataDiskCreateSpec);
...
This example uses the information provided in Creating a Virtual Machine Without a Clone or
Template.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
VMware, Inc. 89
VMware vSphere Automation SDKs Programming Guide
Use guest and system provided defaults for most configuration settings.
"""
guest_os = testbed.config['VM_GUESTOS']
boot_disk = Disk.CreateSpec(type=Disk.HostBusAdapterType.SCSI,
scsi=ScsiAddressSpec(bus=0, unit=0),
new_vmdk=Disk.VmdkCreateSpec())
data_disk = Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec())
nic = Ethernet.CreateSpec(
start_connected=True,
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=standard_network))
boot_device_order = [BootDevice.EntryCreateSpec(BootDevice.Type.ETHERNET),
BootDevice.EntryCreateSpec(BootDevice.Type.DISK)]
vm_create_spec = VM.CreateSpec(name=vm_name,
guest_os=guest_os,
placement=placement_spec,
disks=[boot_disk, data_disk],
nics=[nic],
boot_devices=boot_device_order)
print('\n# Example: create_basic_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(stub_config)
vm = vm_svc.create(vm_create_spec)
vm_info = vm_svc.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm
...
VMware, Inc. 90
VMware vSphere Automation SDKs Programming Guide
and memory information, or networks. Virtual machine settings can be configured when cloning,
registering and relocating an existing virtual machine.
When you create your virtual machine, use the setName method of the CreateSpec class to pass
as argument the display name of the virtual machine.
You must create also a PlacementSpec instance that describes the location of the virtual
machine in regards to the resources of a given vCenter Server instance. Use the
setPlacement(PlacementSpec placement) method of the CreateSpec class to set the placement
information for the virtual machine. You can set one or all of the following vSphere resources:
datastore, cluster, folder, host, and resource pool.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
...
String clusterId =
ClusterHelper.getCluster(stubFactory,
sessionStubConfig,
datacenterName,
clusterName);
System.out.println("Selecting cluster " + clusterName + "(id="
+ clusterId + ")");
String vmFolderId =
FolderHelper.getFolder(stubFactory,
sessionStubConfig,
datacenterName,
vmFolderName);
VMware, Inc. 91
VMware vSphere Automation SDKs Programming Guide
String datastoreId =
DatastoreHelper.getDatastore(stubFactory,
sessionStubConfig,
datacenterName,
datastoreName);
System.out.println("Selecting datastore " + datastoreName + "(id="
+ datastoreId + ")");
/*
* Create the virtual machine placement spec with the datastore, resource pool,
* cluster and vm folder
*/
VMTypes.PlacementSpec vmPlacementSpec = new VMTypes.PlacementSpec();
vmPlacementSpec.setDatastore(datastoreId);
vmPlacementSpec.setCluster(clusterId);
vmPlacementSpec.setFolder(vmFolderId);
return vmPlacementSpec;
}
VMTypes.CreateSpec vmCreateSpec =
new VMTypes.CreateSpec.Builder(this.vmGuestOS)
.setName(DEFAULT_VM_NAME)
.setPlacement(vmPlacementSpec)
.build();
...
}
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
def get_placement_spec_for_resource_pool(stub_config,
datacenter_name,
VMware, Inc. 92
VMware vSphere Automation SDKs Programming Guide
vm_folder_name,
datastore_name):
"""
Returns a VM placement spec for a resourcepool. Ensures that the
vm folder and datastore are all in the same datacenter which is specified.
"""
resource_pool = resource_pool_helper.get_resource_pool(stub_config,
datacenter_name)
folder = folder_helper.get_folder(stub_config,
datacenter_name,
vm_folder_name)
datastore = datastore_helper.get_datastore(stub_config,
datacenter_name,
datastore_name)
# Create the vm placement spec with the datastore, resource pool and vm
# folder
placement_spec = VM.PlacementSpec(folder=folder,
resource_pool=resource_pool,
datastore=datastore)
Hardware Version
The hardware version of a virtual machine reflects the virtual hardware features supported by a
virtual machine. These features depend on the physical hardware available on the ESXi host on
which the virtual machine is running.
Virtual hardware features include the BIOS and Extensible Firmware Interface (EFI), the maximum
number of CPUs, the maximum memory configuration, and other hardware characteristics.
When you create a virtual machine, the default hardware version of the virtual machine is the
most recent version available on the host where the virtual machine is created. For information
about the latest VMware products and virtual hardware versions, see Virtual machine hardware
versions (1003746).
You can set a lower virtual hardware version of a virtual machine than the highest supported
by the ESXi host on which the virtual machine is running. Setting a lower hardware version can
provide flexibility and is useful in the following cases:
VMware, Inc. 93
VMware vSphere Automation SDKs Programming Guide
n In case you do not need the hardware features of the latest hardware version of the host.
Boot Options
You can configure the boot options of a virtual machine by using the setBoot(CreateSpec boot)
method of the CreateSpec class.
The method takes as argument the BootTypes.CreateSpec class. You can select one of the
following settings when booting the virtual machine:
n Delay - Indicates a delay in milliseconds before starting the firmware boot process when the
virtual machine is powered on.
n Retry - Indicates whether the virtual machine automatically retries to boot after a failure.
n Retry delay - Indicates a delay in milliseconds before retrying the boot process after a failure.
n Enter setup mode - If set to true, indicates that the firmware boot process automatically
enters BIOS setup mode the next time the virtual machine boots. The virtual machine resets
this flag to false once it enters setup mode.
n EFI legacy boot - If set to true, indicates that the EFI legacy boot mode is used.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
...
this.bootService = vapiAuthHelper.getStubFactory().createStub(Boot.class,
this.sessionStubConfig);
// Save the current boot info to verify that we have cleaned up properly
VMware, Inc. 94
VMware vSphere Automation SDKs Programming Guide
this.originalBootInfo = bootInfo;
System.out.println(
"\n\n#### Example: Update firmware to EFI for boot configuration.");
BootTypes.UpdateSpec bootUpdateSpec = new BootTypes.UpdateSpec.Builder()
.setType(BootTypes.Type.EFI)
.build();
this.bootService.update(this.vmId, bootUpdateSpec);
System.out.println(bootUpdateSpec);
bootInfo = this.bootService.get(this.vmId);
System.out.println(bootInfo);
System.out.println(
"\n\n#### Example: Update boot firmware to tell it to enter setup"
+ " mode on next boot.");
bootUpdateSpec = new BootTypes.UpdateSpec.Builder()
.setEnterSetupMode(true)
.build();
this.bootService.update(this.vmId, bootUpdateSpec);
System.out.println(bootUpdateSpec);
bootInfo = this.bootService.get(this.vmId);
System.out.println(bootInfo);
System.out.println(
"\n\n#### Example: Update firmware to introduce a delay in boot "
+ "process and automatically reboot after a failure to boot, "
+ "retry delay = 30000 ms.");
bootUpdateSpec = new BootTypes.UpdateSpec.Builder()
.setDelay(10000l)
.setRetry(true)
.setRetryDelay(30000l)
.build();
this.bootService.update(this.vmId, bootUpdateSpec);
bootInfo = this.bootService.get(this.vmId);
System.out.println(bootInfo);
...
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
"""
Demonstrates how to configure the settings used when booting a virtual machine.
Sample Prerequisites:
The sample needs an existing VM.
"""
VMware, Inc. 95
VMware vSphere Automation SDKs Programming Guide
vm = None
vm_name = None
stub_config = None
boot_svc = None
cleardata = False
orig_boot_info = None
...
def run():
global vm
vm = get_vm(stub_config, vm_name)
if not vm:
exit('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Boot Sample".format(vm_name, vm))
print('\n# Example: Update boot firmware to tell it to enter setup mode on '
'next boot')
update_spec = Boot.UpdateSpec(enter_setup_mode=True)
print('vm.hardware.Boot.update({}, {})'.format(vm, update_spec))
boot_svc.update(vm, update_spec)
boot_info = boot_svc.get(vm)
print('vm.hardware.Boot.get({}) -> {}'.format(vm, pp(boot_info)))
VMware, Inc. 96
VMware vSphere Automation SDKs Programming Guide
...
When you create a virtual machine, you specify the guest operating system by using the
setGuestOS(GuestOS guestOS) method of the VMTypes.CreateSpec class. The GuestOS class
defines the valid guest OS types that you can choose from for configuring a virtual machine.
After the create operation finishes successfully, you can install the guest operating system
on the mew virtual machine in the same way as you install it on a physical machine. For
further information on installing a guest operating system, refer to the Guest Operating System
Installation Guide at http://partnerweb.vmware.com/GOSIG/home.html and the vSphere Virtual
Machine Administration guide.
Starting with vSphere 7.0, you can use the vSphere Automation APIs to install the VMware
Tool on the quest operating system and perform some guest OS customizations. See Installing
VMware Tools.
To change the CPU and memory configuration settings, use the CpuTypes.UpdateSpec and
MemoryTypes.UpdateSpec classes.
CPU Configuration
You can set the number of CPU cores in the virtual machine by using the setCount
method of the CpuTypes.UpdateSpec class. The supported range of CPU cores depends on
the guest operating system and virtual hardware version of the virtual machine. If you set
CpuTypes.Info.getHotAddEnabled() and CpuTypes.Info.getHotRemoveEnabled() to true, you
allow virtual processors to be added or removed from the virtual machine at runtime.
Memory Configuration
You can set the memory size of a virtual machine by using the setSizeMiB method of
the MemoryTypes.UpdateSpec class. The supported range of memory sizes depends on the
configured guest operating system and virtual hardware version of the virtual machine. If you set
MemoryTypes.UpdateSpec.setHotAddEnabled() to true while the virtual machine is not powered
on, you enable adding memory while the virtual machine is running.
VMware, Inc. 97
VMware vSphere Automation SDKs Programming Guide
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
this.memoryService = vapiAuthHelper.getStubFactory().createStub(Memory.class,
this.sessionStubConfig);
this.cpuService = vapiAuthHelper.getStubFactory().createStub(Cpu.class,
this.sessionStubConfig);
// Update the number of cores per socket in the virtual machine and
// allow CPU cores to be added to the virtual machine while it is running
cpuUpdateSpec = new
CpuTypes.UpdateSpec.Builder().setCoresPerSocket(2l).setHotAddEnabled(true).build();
cpuService.update(this.vmId, cpuUpdateSpec);
...
VMware, Inc. 98
VMware vSphere Automation SDKs Programming Guide
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
The following example shows how you can update the CPU configuration of a virtual machine.
...
vm = None
vm_name = None
stub_config = None
cpu_svc = None
cleardata = False
orig_cpu_info = None
...
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server,
username,
password,
skip_verification)
...
def run():
global vm
vm = get_vm(stub_config, vm_name)
if not vm:
exit('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Cpu Sample".format(vm_name, vm))
VMware, Inc. 99
VMware vSphere Automation SDKs Programming Guide
The following example demonstrates how you can add memory to a running virtual machine.
...
vm = None
vm_name = None
stub_config = None
memory_svc = None
cleardata = False
orig_memory_info = None
...
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server,
username,
password,
skip_verification)
...
global vm
vm = get_vm(stub_config, vm_name)
if not vm:
exit('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Memory Sample".format(vm_name, vm))
...
Networks
You configure network settings so that a virtual machine can communicate with the host and with
other virtual machines. When you configure a virtual machine, you can add network adapters
(NICs) and specify the adapter type.
You can add virtual Ethernet adapters to a virtual machine by using the
VMTypes.CreateSpec.setNics method. Pass as argument a List of EthernetTypes.CreateSpec
objects that provide the configuration information of the created virtual Ethernet
adapters. You can set the MAC address type to EthernetTypes.MacAddressType.MANUAL,
EthernetTypes.MacAddressType.GENERATED, or EthernetTypes.MacAddressType.ASSIGNED. Select
MANUAL to specify the MAC address explicitly.
You can specify also the physical resources that back a virtual Ethernet adapter by
using the EthernetTypes.BackingSpec.setType method. The method takes as argument
one of the following types: EthernetTypes.BackingType.STANDARD_PORTGROUP, HOST_DEVICE,
DISTRIBUTED_PORTGROUP, or OPAQUE_NETWORK.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
...
this.ethernetService = vapiAuthHelper.getStubFactory().createStub(
Ethernet.class, this.sessionStubConfig);
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
vm = None
vm_name = None
stub_config = None
ethernet_svc = None
cleardata = False
nics_to_delete = []
orig_nic_summaries = None
...
global vm
vm = get_vm(stub_config, vm_name)
if not vm:
exit('Sample requires an existing vm with name ({}). '
'Please create the vm first.'.format(vm_name))
print("Using VM '{}' ({}) for Disk Sample".format(vm_name, vm))
global nics_to_delete
You can retrieve a list of virtual machines in a single vCenter Server instance by filtering the
results based on a specific requirement. For example, you can use as filter criteria the power
state of the virtual machines, or the host, cluster, data center, folder, or resource pool that must
contain the virtual machines. In case you specify multiple filter criteria, only virtual machines that
match all filter criteria are returned.
To retrieve a list of the virtual machines that match your specific criteria, call the list methods
of the VM service. The method takes as parameter the VMTypes.FilterSpec instance that you can
use to provide your filter criteria.
The following code example shows how you can retrieve the VM ID of a virtual machine with a
specific name.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
return vmList.get(0).getVm();
}
...
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
if len(vms) == 0:
print('No vm found')
return None
Before you install VMware tools, you must install and boot the guest operating system.
To mount and unmount the VMware Tools installer CD as a CD-ROM for the guest operating
system, use the methods of the com.vmware.vcenter.vm.tools.Installer interface.
To mount the VMware Tools, call the connect(vm_ID) method of the Installer interface. On
Windows guest operating systems with activated Autorun feature, this method automatically
initiates the installation of the VMware Tools and requires a user input to complete. On other
guest operating systems, this method only mounts the VMware Tools disk image on the virtual
CD/DVD drive and the user is required to do some guest OS-specific actions. For example,
for some Linux distributions, the user is required to extract the contents of the VMware Tools
installation archive and run the installer.
To unmount the VMware Tools installer CD image from the virtual CD/DVD drive, call the
disconnect(vm_ID) method of the Installer interface.
To monitor the status of the VMware Tools installation, you can first retrieve the properties of the
VMware Tools by calling the get(vm_VM) method of the com.vmware.vcenter.vm.Tools interface.
The method returns a ToolsTypes.Info object which you can use to call the getVersionStatus()
and getRunState() methods.
To upgrade the VMware Tools, call the upgrade(vm_ID, commandLineOptions) method of the
Tools interface. The method takes as arguments the ID of the virtual machine on which the
VMware Tools is installed and running. Use the commandLineOptions argument to specify the
command-line options that you want to pass to the installer to modify the tools installation
procedure. You can monitor the upgrade operation in the same way you monitor the installation
operation.
To update the properties of the VMware Tools, call the update(vm_ID, update_spec) method
of the Tools interface. Pass as argument a ToolsTypes.UpdateSpec object and define the tools
upgrade policy settings for the virtual machine by calling the setUpgradePolicy(upgradePolicy)
method.
n PowerTypes.State.POWERED_OFF - Indicates that the virtual machine is not running. You can
still update the software on the physical disk of the virtual machine, which is impossible for
physical machines.
To perform a power operation on a virtual machine, you can use one of the methods of the Power
class. Before you call one of the methods to change the power state of a virtual machine, you
must first check the current state of the virtual machine by using the Power.get method. Pass as
argument the virtual machine identifier.
n Power.start - Powers on a powered off or suspended virtual machine. The method takes as
argument the virtual machine identifier.
n Power.stop - Powers off a powered on or suspended virtual machine. The method takes as
argument the virtual machine identifier.
n Power.suspend - Pauses all virtual machine activity for a powered on virtual machine. The
method takes as argument the virtual machine identifier.
n Power.reset - Shuts down and restarts the guest operating system without powering off the
virtual machine. Although this method functions as a stop method that is followed by a start
method, the two operations are atomic with respect to other clients, meaning that other
power operations cannot be performed until the reset method completes.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
...
this.powerService = vapiAuthHelper.getStubFactory().createStub(
Power.class, this.sessionStubConfig);
this.vmId = VmHelper.getVM(vapiAuthHelper.getStubFactory(),
sessionStubConfig,
vmName);
this.powerService.start(this.vmId);
...
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
vm = None
vm_name = None
stub_config = None
# Create the Power stub for running power operations on virtual machines
vm_power_svc = Power(stub_config)
vm_power_svc.start(vm)
Server inventory, it becomes unusable. Virtual machine files remain in the same datastore but
you cannot power on the virtual machine when it is not registered in the inventory.
You can temporarily remove a virtual machine from vCenter Server by unregistering it. Virtual
machine files are not deleted from the datastore. Though all high-level information about the
virtual machine such as statistics, resource pool association, permissions, and alarms, is removed
from the host and the vCenter Server instance. To remove a virtual machine from the inventory,
call the unregister(vm_ID) method of the VM service and pass as argument the ID of the virtual
machine.
To restore a virtual machine to the vCenter Server inventory, and make it usable again,
call the register(register_spec) method of the VM service. You pass as argument a
VMTypes.RegisterSpec instance that contains information about the current location of the virtual
machine files on the datastore. You can also define the location within the vCenter Server
inventory, for example, the cluster, folder, or the host, where you want to register the virtual
machine. After registration, the virtual machine takes its resources (CPU, memory, and so on)
from the resource pool or host to which it is registered.
If you no longer need a virtual machine and you want to free up datastore space, you can
permanently delete a virtual machine from the inventory. Call the delete(vm_ID) method of the
VM service and pass as argument the ID of the virtual machine. Upon a successful completion
of the operation, the virtual machine files are removed from the datastore, including the
configuration file and the virtual disk files.
Before you perform operations on the guest operating system, you must prepare the
environment. You must create the Process.CreateSpec for initiating processes in the guest
and create the Transfer.CreateSpec for the file transfer to or from the guest. The content of
the optional FileAttributeCreateSpec associated with the Transfer.CreateSpec establishes the
direction of the transfer and controls guest operating system specific file attributes. You must
set up equivalent _download and _upload functions for URL management of the file transfer to or
from the guest. You can also create an argument parser for standard inputs, such as server, user
name, and password, and you can add custom input arguments.
Procedure
1 Find the virtual machine on which the guest operating system runs, verify that VMware Tools
is running, and provide credentials.
2 Create a temporary directory from which to run the script and capture any output.
5 Start the script and capture stdout and stderr in the temporary files that you created earlier.
8 Clean up the temporary files and directories on the guest operating system.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
# Create the Transfer.CreateSpec for the file transfer to/from the guest
def _create_transfer_spec(self,
path,
attributes=None):
return Transfers.CreateSpec(attributes=attributes,
path=path)
owner_id=None,
group_id=None,
permissions=None):
posix = Transfers.PosixFileAttributesCreateSpec(owner_id=owner_id,
group_id=group_id,
permissions=permissions)
return Transfers.FileCreationAttributes(size,
overwrite=overwrite,
last_modified=last_modified,
last_accessed=last_accessed,
posix=posix)
def _download(self,
url,
expectedLen=None):
urloptions = urlparse(url)
# Skip server cert verification.
# This is not recommended in production code.
conn = httpclient.HTTPSConnection(urloptions.netloc,
context=ssl._create_unverified_context())
return body
return res
def __init__(self):
# Create argument parser for standard inputs:
# server, username, password, cleanup and skipverification
parser = sample_cli.build_arg_parser()
action='store',
help='Name of the testing vm')
parser.add_argument('--root_user',
action='store',
help='Administrator account user name')
parser.add_argument('--root_passwd',
action='store',
help='Administrator account password')
args = sample_util.process_cli_args(parser.parse_args())
self.vm_name = args.vm_name
self.root_user = args.root_user
self.root_passwd = args.root_passwd
self.cleardata = args.cleardata
def run(self):
# Using vAPI to find VM.
filter_spec = VM.FilterSpec(names=set([self.vm_name]))
vms = self.client.vcenter.VM.list(filter_spec)
if len(vms) != 1:
raise Exception('Could not locate the required VM with name ' +
self.vm_name + '. Please create the vm first.')
if vms[0].power_state != 'POWERED_ON':
raise Exception('VM is not powered on: ' + vms[0].power_state)
vm_id = vms[0].vm
# Establish the user credentials that will be needed for all Guest Ops APIs.
creds = Credentials(interactive_session=False,
user_name=self.root_user,
password=self.root_passwd,
type=Credentials.Type.USERNAME_PASSWORD)
# Step 2 - Create a temporary directory from which to run the command and capture any
output
tempDir = self.client.vcenter.vm.guest.filesystem.Directories.create_temporary(
vm_id, creds, '', '', parent_path=None)
# Step 5 - Start the program on the guest, capturing stdout and stderr in the
separate temp files obtained earlier.
options = (" > " + stdout + " 2> " + stderr)
spec = self._process_create_spec(scriptPath,
args=options,
dir=tempDir)
pid = self.client.vcenter.vm.guest.Processes.create(vm_id, creds, spec)
print('process created with pid: %s\n' % pid)
# Step 6 - Need a loop to wait for the process to finish to handle longer running
processes.
while True:
time.sleep(1.0)
try:
# List the single process for pid.
result = self.client.vcenter.vm.guest.Processes.get(vm_id,
creds,
pid)
if result.exit_code is not None:
print('Command: ' + result.command)
print('Exit code: %s\n' % result.exit_code)
break
if result.finished is None:
print('Process with pid %s is still running.' % pid)
continue
except Exception as e:
raise e
...
Data sets provide a communication infrastructure that you can use to share information between
the host and guest. This information can then be used by guest agents or applications to
configure the guest itself or guest applications. The information is grouped into data sets,
each of which contains key-value entries comprising the data. Each application that uses the
service should have at least one unique data set in which to store its data to avoid conflict with
other applications. Each data set has attributes that define its access control and interoperability
configuration.
Note You should not store sensitive data, such as passwords or private keys, in plain text.
To perform data set operations, the virtual machine must be running virtual hardware version 20
or later.
You should modify each data set by using the application that originally created that data set. If
your application modifies a data set owned by another application, the other application might
stop working.
For more information about data sets, see vSphere Virtual Machine Administration and the
VMware Guest SDK Programming Guide.
You can use data set operations to share information between a virtual machine and its
guest operating system. The available operations include listing data sets, retrieving data set
information, creating, modifying, and deleting a data set. You can also manipulate individual
entries in a data set. The available operations include listing entry keys in a data set, retrieving
the value of an entry in a data set, modifying and deleting an entry in a data set.
Operation Description
List data sets You can list all available data sets of a virtual machine.
Get data set You can retrieve information about a specific data set.
Update data set You can modify the attributes of a data set.
List data set entry keys You can list all entry keys in a data set.
Get data set entry key value You can retrieve the value of a specific entry in a data set.
Set data set entry key value You can create or update an entry in a data set. If
the new entry does not contain a key that matches an
existing key, the operation creates a new entry. If the new
entry contains a key that matches an existing key, the
new key overwrites the value of the existing key.
Delete data set entry key value You can delete an entry in a data set.
You can use content libraries to share VM and vApp templates, and other types of files, such as
ISO images, text files, and so on, across the vCenter Server instances in the same or different
locations. Sharing templates across your virtual environment promotes consistency, compliance,
efficiency, and automation in deploying workloads at scale.
You use library items to store and manage content in a content library. A single library item can
contain one or more files. For example, an OVF package consists of a .vmdk file, manifest file,
and others, but it is represented by a single library item.
Starting with vSphere 7.0 Update 3, you can add a security policy to a local or subscribed
content library and thus protect your system when you synchronize or download library content
from third party providers.
n Content Libraries
The Content Library API provides services that allow you to create and manage content
libraries programmatically. You can create a local library and publish it for the entire virtual
environment. You can also subscribe to use the contents of a local library and enable
automatic synchronization to ensure that you have the latest content.
n Library Items
A library item groups multiple files within one logical unit. You can perform various tasks with
the items in a content library.
You create and manage the content of a content library on a single vCenter Server instance, but
you can distribute the content to other vCenter Server instances. Depending on your needs, you
can maintain two types of content libraries: local and subscribed. You can shape the contents of
a library item and then combine several library items in a local content library. Furthermore, you
can publish the library to make its content available to other users.
Local library.
You can create a local library as the source for content you want to save or share. Create
the local library on a single vCenter Server instance. You can add items to a local library
or remove them. You can publish a local library and as a result this content library service
endpoint can be accessed by other vCenter Server instances in your virtual environment.
When you publish a library, you can configure a password for authentication.
Subscribed library.
You can create a subscribed library and populate its content by synchronizing to a local
library. A subscribed library contains copies of the local library files or just the metadata of
the library items. The local library can be located on the same vCenter Server instance as
the subscribed library, or the subscribed library can reference a local library on a different
vCenter Server instance. You cannot add library items to a subscribed library. You can only
add items to the source library. After synchronization, both libraries will contain the same
items.
VMs and vApps have several files, such as log files, disk files, memory files, and snapshot files
that are part of a single library item. You can create library items in a specific local library or
remove items from a local library. You can also upload files to an item in a local library so that the
libraries subscribed to it can download the files to their NFS or SMB server, or datastore.
For information about the tasks that you can perform by using the content library service, see
Content Libraries.
Depending on the type of storage that you have, you can use Virtual Machine File System
(VMFS) or Network File System (NFS) for storing content on a datastore.
For storing content on a remote file system, you can enter the path to the NFS storage that
is mounted on the Linux file system of the vCenter Server instance. For example, you can use
the following URI formats: nfs://<server>/<path>?version=4 and nfs://<server>/<path>. If you
have a vCenter Server instance that runs on a Windows machine, you can specify the Server
Massage Block (SMB) URI to the Windows shared folders that store the library content. For
example, you can use the following URI format: smb://<unc-server>/<path>.
For more information about storing the contents of a local library, see Content Library Storage.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
/*
* Pass the value of the datastore ManagedObjectReference.
* See the vSphere Web Services SDK Programming Guide
* and the vSphere Web Services SDK samples. In addition, the vSphere
Automation SDK for Java provides
* the VimUtil utility class in the vmware.samples.vim.helpers package.
* You can use the utility to retrieve the ManagedObjectReference
* of the datastore entity.
*/
libraryBacking.setDatastoreId("datastore-123");
For more information about storing the contents of a local library, see Content Library Storage.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
You can use the list function to retrieve all local and subscribed libraries in your system.
This example uses the steps that are described in Listing All Content Libraries.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example uses the steps that are described in Listing All Content Libraries.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
library_stub = content_client.Library(my_stub_config)
libraries = library_stub.list()
print(’List of all library identifiers:’)
for library_id in library_ids :
library = library_stub.get(library_id)
print(’Library ID {}: {}’.format(library_id, library.name))
If you want to retrieve only a list of the local libraries, you must retrieve the LocalLibrary service
and use the list function on the LocalLibrary service. To list only subscribed libraries, you
must retrieve the SubscribedLibrary service and call the list function on the SubscribedLibrary
service.
To a filter with specific search criteria, call the find (find_spec) function of the Library service.
Pass as argument a LibraryTypes.FindSpec instance that contains your search criteria. Upon a
successful completion of the call, you receive a list of all content libraries that match your search
criteria.
Java Example of Retrieving a List of All Local Libraries with a Specific Name
This example retrieves a list of all local libraries with the name AcmeLibrary that exist in your
virtual environment.
Note For related code samples, see the vsphere-automation-sdk-java VMware repository at
GitHub.
...
findSpec.setType(LibraryType.LOCAL);
List<String> ids = libraryService.find(findSpec);
Python Example of Retrieving a List of All Local Libraries with a Specific Name
This example retrieves a list of all local libraries with the name AcmeLibrary that exist in your
virtual environment.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
...
Content Libraries
The Content Library API provides services that allow you to create and manage content
libraries programmatically. You can create a local library and publish it for the entire virtual
environment. You can also subscribe to use the contents of a local library and enable automatic
synchronization to ensure that you have the latest content.
Prerequisites
Required privileges:
n Content library.Create local library on the vCenter Server instance where you want to create
the library.
Procedure
1 Access the LocalLibrary service that provides support for creating local content libraries.
3 (Optional) Create a SecurityPolicies instance to define the security policy rules for the
library. For vSphere 7.0 Update3, you can only define rules for an OVF and OVA templates
in the library by using the OVF_STRICT_VERIFICATION security rule. When the OVF security
policy is configured for a local content library, an OVF or OVA template can be synchronized
or imported to the library only after its certificate is validated against a trusted certificate
authority.
4 Create a LibraryModel instance and set the properties of the new local library.
If you want to apply a security policy on the local library, you must
use the setSecurityPolicyId(java.lang.String securityPolicyId) method or the
security_policy_id parameter of the LibraryModel instance.
5 Call the create function on the LocalLibrary object and pass the LibraryModel as a
parameter.
Results
A local content library is created on the vCenter Server instance and you can edit its contents.
What to do next
You maintain the contents of the local library by managing its library items. See Library Items and
Content Library Support for OVF and OVA Packages. You can also share the library content by
publishing the local library. See Publish an Existing Content Library.
This example uses the steps that are described in the Create a Local Content Library procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
// Create a StorageBacking instance to back the library content on the local file system.
StorageBacking libraryBacking = new StorageBacking();
libraryBacking.setType(Type.OTHER);
libraryBacking.setStorageUri(URI.create("file:///tmp"));
libraryModel.setStorageBackings(Collections.singletonList(libraryBacking));
This example uses the steps that are described in the Create a Local Content Library procedure.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
...
Procedure
5 (Optional) If you publish the library with basic authentication, you must specify a user name
and password for the PublishInfo instance, which must be used for authentication.
Important Use the predefined user name vcsp or leave the user name undefined. You must
set only a password to protect the library.
7 Use the retrieved local library to configure it with the PublishInfo instance.
8 Update the properties of the LibraryModel object returned for the local library.
This example uses the steps that are described in the Publish an Existing Content Library
procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
// Set the local library to published and update the library instance.
publishInfo.setPublished(true);
libraryModel.setPublishInfo(publishInfo);
localLibraryService.update(libraryModel.getId(), libraryModel);
This example uses the steps that are described in the Publish an Existing 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.
...
publish_info.authentication_method = library_client.PublishInfo.AuthenticationMethod.BASIC
publish_info.published = True
Procedure
You can enable either basic authentication or no authentication on the library. Basic
authentication requires a user name and password.
4 (Optional) If you publish the library with basic authentication, you must specify a user name
and password for the PublishInfo instance, which must be used for authentication.
Important Use the predefined user name vcsp or leave the user name undefined. You must
set only a password to protect the library.
5 (Optional) Create a SecurityPolicies instance to define the security policy rules for the
library. For vSphere 7.0 Update3, you can only define rules for an OVF and OVA templates
in the library by using the OVF_STRICT_VERIFICATION security rule. When the OVF security
policy is configured for a local content library, an OVF or OVA template can be synchronized
or imported to the library only after its certificate is validated against a trusted certificate
authority.
If you want to apply a security policy on the local library, you must
use the setSecurityPolicyId(java.lang.String securityPolicyId) method or the
security_policy_id parameter of the LibraryModel instance.
7 Set the library type to local and use the configured PublishInfo instance to set the library to
published.
8 Define where the content of the local library is stored by using the StorageBacking class.
Note If you subscribe to libraries created with basic authentication on a vCenter Server instance,
make sure that you pass vcsp as an argument for the user name.
Prerequisites
Required privileges:
n Content library.Create subscribed library on the vCenter Server instance where you want to
create the library.
Procedure
1 Create a StorageBacking instance to define the location where the content of the subscribed
library is stored.
You can select between no authentication and basic authentication depending on the
settings of the published library you subscribe to. If the library is published with basic
authentication, you must set the basic authentication in the SubscriptionInfo instance.
To match the credentials of the published library, set the user name and the password of
the SubscriptionInfo instance.
b Provide the URL to the endpoint where the metadata of the published library is stored.
You can select between two synchronization modes: automatic and on demand. If you
enable automatic synchronization for a subscribed library, both the content and the
metadata are synchronized with the published library. To save storage space, you can
synchronize the subscribed library on demand and update only the metadata for the
published library content.
d Set the thumbprint that is used for validating the certificate of the published library.
4 Access the SubscribedLibrary service and create the subscribed library instance.
This example uses the steps that are described in the Subscribe to a Content Library procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
// Specify that the content of the subscribed library will be downloaded immediately.
subscriptionInfo.setAutomaticSyncEnabled(true);
subscriptionInfo.setSslThumbprint("9B:00:3F:C4:4E:B1:F3:F9:0D:70:47:48:E7:0B:D1:A7:0E:DE:60:A5
");
// Attach the storage backing and the subscription info to the library model.
libraryModel.setStorageBackings(Collections.singletonList(libraryBacking));
libraryModel.setSubscriptionInfo(subscriptionInfo);
This example uses the steps that are described in the Subscribe to 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.
...
# Attach the storage backing and the subscription info to the library model.
library_model.storage_backings = [library_backing]
library_model.subscription_info = subscription_info
n You can enable automatic synchronization of the subscribed library and download a copy of
the content of the local library immediately.
n You can save storage space and download only the metadata for the items that are part of
the local library.
To ensure that your subscribed library contains the most recent published library content, you
can force a synchronization task.
Procedure
Results
The synchronization operation depends on the update settings of the subscribed library. If the
subscribed library is configured to update only on demand, only the metadata of the library items
will be synchronized.
Local content library You can change the settings of a local library before
calling the update function on the LocalLibrary object:
Before a library is published, you can edit the name,
description, version, and so on.
After a library is published, you must first retrieve the
PublishInfo instance of the published library you want.
You can use the instance to configure the following
settings.
n Unpublish the local library.
n Change the authentication method of the library.
n Change the password that must be used for
authentication.
Subscribed content library You can edit the settings of a subscribed library if you
retrieve the SubscriptionInfo instance associated with it.
To apply the changes, you must update the library by
using the SubscribedLibrary object.
You can configure the following settings:
n The authentication method required by the local
library
n The user name and password of the subscribed library
for authentication to the local library
n The method for synchronizing the metadata and the
content of the subscribed library
n The thumbprint used for validating the SSL certificate
of the local library
Note Starting with vSphere 7.0 Update 3, you can use the Security Policies service to secure
a content library. You can set, update, or remove a security policy when you update a local or
subscribed content library.
You can create a subscribed library with the option to download the library content on demand.
As a result, only the metadata for the library items is stored in the associated with the subscribed
library storage. When you want to deploy a virtual machine from a VM temple in the subscribed
library, you must synchronize the subscribed library to download the entire published library
content. When you no longer need the VM template, you can call the evict function on the
SubscribedLibrary service. You must provide the subscribed library ID to this function. As a
result, the subscribed library content that is cached on the backing storage is deleted.
Procedure
1 Access the SubscribedLibrary or the LocalLibrary service by using the vSphere Automation
Endpoint.
3 Call the delete function on the library service and pass the library ID as argument.
All library items cashed on the storage backing are removed asynchronously. If this operation
fails, you must manually remove the content of the library.
Library Items
A library item groups multiple files within one logical unit. You can perform various tasks with the
items in a content library.
You can upload files to a library item in a local library and update existing items. You can
download the content of a library item from a subscribed library and use the item, for example,
to deploy a virtual machine. You can remove the content of a library item from a subscribed
library to free storage space and keep only the metadata of the library item. When you no longer
need local library items, you can delete them and they are removed from the subscribed library
when a synchronization task is completed.
You can create a library item from a specific item type, for example .ovf and VM template. The
Content Library service must support the library item type to handle the item correctly. If no
support is provided for a specified type, the Content Library service handles the library item in
the default way, without adding metadata to the library item or guiding the upload process.
For information about the supported VM template types, see the vSphere Virtual Machine
Administration documentation.
Procedure
5 Invoke the create function on the Item object to pass the library item specification and the
unique client token.
What to do next
Upload content to the new library item. See Upload a File from a Local System to a Library Item
and Upload a File from a URL to a Library Item.
This example uses the steps that are described in the Create an Empty Library Item procedure.
Note For related code samples, see the vsphere-automation-sdk-java VMware repository at
GitHub.
...
// Create an instance of the ItemModel class and specify the item settings.
ItemModel libItemSpec = new ItemModel();
libItemSpec.setName("ESXi ISO image");
libItemSpec.setDescription("ISO image with the latest security patches for ESXi");
libItemSpec.setType("iso");
This example uses the steps that are described in the Create an Empty Library Item procedure.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
...
# 1 - Create an instance of the ItemModel class and specify the item settings.
item_model = library_client.ItemModel()
item_model.name = ’ESXi ISO image’
item_model.description = ’ISO image with the latest security patches for ESXi’
item_model.type = ’iso’
# 3 - Create the new instance of the Item class, using the specified model.
idem_token = str(uuid.uuid4())
item_stub = library_client.Item(my_stub_config)
item_id = item_stub.create(create_spec=item_model, client_token=idem_token)
You can retrieve a list of all items in a library, retrieve a library item that has a specific type or
name, and find a library item that is not cached on the disk. You can then update the library item
content from the subscribed library.
Prerequisites
Procedure
1 Retrieve the ID of the content library whose items you want to list.
Example
You can see an example query operation in the code example for Edit the Settings of a Library
Item. The beginning of the example lists the items of a published library and prints a list with the
names and size of each file in the listed items.
Prerequisites
Procedure
Results
Prerequisites
Procedure
This example uses the steps that are described in the Edit the Settings of a Library Item
procedure.
Note For related code samples, see the vsphere-automation-sdk-java VMware repository at
GitHub.
...
// List the files uploaded to each library item and print their names and size
com.vmware.content.library.item.File itemFilesService =
this.vapiAuthHelper.getStubFactory().createStub(com.vmware.content.library.item.File.class,
sessionStubconfig);
List<com.vmware.content.library.item.FileTypes.Info> fileInfos =
itemFilesService.list(itemId);
for (com.vmware.content.library.item.FileTypes.Info singleFile : fileInfos) {
System.out.println("Library item with name "+ singleFile.getName() + " has
size
" + singleFile.getSize());
}
// Change the name and description of the library item with the specified name
if (singleItem.getName().equals("simpleVmTemplate")) {
ItemModel libItemUpdated = new ItemModel();
libItemUpdated.setName("newItemName");
libItemUpdated.setDescription("Description of the newItemName");
libItemService.update(singleItem.getId(), libItemUpdated);
}
}
This example uses the steps that are described in the Edit the Settings of a Library Item
procedure.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
...
# 2 - List the files uploaded to each library item and print their names and sizes.
file_stub = item_client.File(my_stub_config)
for item_id in item_ids :
item = item_stub.get(item_id)
file_infos = file_stub.list(item_id)
for file_info in file_infos :
print(’Library item {} has file {} with size {}’.format(item.name, file_info.name,
file_info.size))
Prerequisites
n Verify that you have access to the UpdateSession and File services.
Procedure
1 Create an UpdateSessionModel instance to track the changes that you make to the library
item.
3 Create an AddSpec instance to describe the upload method and other properties of the file to
be uploaded.
4 Create the request for changing the item by using the File service.
6 Complete and delete the update session to apply the changes to the library item.
This example uses the steps that are described in the Upload a File from a Local System to a
Library Item procedure.
Note For related code samples, see the vsphere-automation-sdk-java VMware repository at
GitHub.
...
// Create an UpdateSessionModel instance to track the changes you make to the item.
UpdateSessionModel updateSessionModel = new UpdateSessionModel();
updateSessionModel.setLibraryItemId(newItem);
// Create a new AddSpec instance to describe the properties of the file to be uploaded.
// Use the HTTP library to upload the file to the library item.
URI uploadUri = fileInfo.getUploadEndpoint().getUri();
java.io.File file = new java.io.File("/updates/esxi/esxi_patch.iso");
String transferUrl = uploadUri.toURL().toString();
httpClient.upload(file, transferUrl);
This example uses the steps that are described in the Upload a File from a Local System to a
Library Item procedure.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
...
# 1 - Create an instance of the ItemModel class and specify the item settings.
item_model = library_client.ItemModel()
item_model.name = ’ESXi patches’
item_model.description = ’ESXi security patches’
item_model.type = ’iso’
item_model.library_id = my_library_id
idem_token = str(uuid.uuid4())
item_stub = library_client.Item(my_stub_config)
item_id = item_stub.create(create_spec=item_model,
client_token=idem_token)
# 2 - Create an UpdateSessionModel instance to track the changes you make to the item.
update_session_model = item_client.UpdateSessionModel()
update_session_model.library_item_id = item_id
try :
# 4 - Create a new AddSpec instance to describe the properties of the file to be uploaded.
file_spec = update_session_client.AddSpec()
file_spec.name = ’ESXi patch’
file_spec.source_type = update_session_client.File.SourceType.PUSH
finally :
# 8 - Delete the session.
library_item_service.UpdateSession.delete(session_id)
Prerequisites
n Verify that you have access to the UpdateSession and File services.
Procedure
1 Create an UpdateSessionModel instance to track the changes that you make to the library
item.
3 Create a file specification to describe the upload method and other properties of the file to
be uploaded.
6 Create a request for changing the item by using the configured file specification.
7 Complete the update session to apply the changes to the library item.
This example uses the steps that are described in the Upload a File from a URL to a Library Item
procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
...
// Create an UpdateSessionModel instance to track the changes you make to the item.
UpdateSessionModel updateSessionModel = new UpdateSessionModel();
updateSessionModel.setLibraryItemId(newItem);
// Create a new AddSpec instance to describe the properties of the file to be uploaded.
FileTypes.AddSpec fileSpec = new AddSpec();
fileSpec.setName("ESXi patch");
fileSpec.setSourceType(SourceType.PULL);
// Specify the location from which the file is uploaded to the library item.
TransferEndpoint endpoint = new TransferEndpoint();
endpoint.setUri(URI.create("http://www.acme.com/patches_ESXi65/ESXi_patch.iso"));
fileSpec.setSourceEndpoint(endpoint);
uploadFileService.add(sessionId, fileSpec);
This example uses the steps that are described in the Upload a File from a URL to a Library Item
procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
# 2 - Create an UpdateSessionModel instance to track the changes you make to the item.
update_session_model = item_client.UpdateSessionModel()
update_session_model.library_item_id = item_id
try :
# 4 - Create a new AddSpec instance to describe the properties of the file to be uploaded.
file_spec = update_session_client.AddSpec()
file_spec.name = ’ESXi patch’
file_spec.source_type = update_session_client.File.SourceType.PULL
# 5 - Specify the location from which the file is to be uploadod to the library item.
endpoint = item_client.TransferEndpoint()
endpoint.uri = ’http://www.example.com/patches_ESXi65/ESXi_patch.iso’
file_spec.source_endpoint = endpoint
Procedure
1 Create a download session model to specify the item, which contains the file that you want to
download.
2 Access the File service and retrieve the file that you want to export to your system within
the new download session.
3 Prepare the files that you want to download and wait until the files are in the prepared state.
Java Example of Downloading Files from a Library Item to Your Local System
This example is based on the code in the ItemDownloadHelper.java sample file.
This example uses the steps that are described in the Download Files to a Local System from a
Library Item procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
// Access the File service and retrieve the files you want to export.
File downloadFileService = vapiAuthHelper.getStubFactory().createStub(File.class,
sessionStubConfig);
List<FileTypes.Info> downloadFileInfos = downloadFileService.list(downloadSessionId);
for (FileTypes.Info downloadFileInfo : downloadFileInfos) {
// Make sure all files are in the prepared state before you precede with the downloading
operation.
downloadFileService.prepare(downloadSessionId, downloadFileInfo.getName(),
EndpointType.HTTPS);
long timeOut = 360;
Long endTime = System.currentTimeMillis() + timeOut * 1000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
FileTypes.PrepareStatus expectedStatus =
com.vmware.content.library.item.downloadsession.File.PrepareStatus.PREPARED;
downloadFileInfo = downloadFileService.get(downloadSessionId,
downloadFileInfo.getName());
FileTypes.PrepareStatus currentStatus = downloadFileInfo.getStatus();
if (currentStatus == expectedStatus) {
// When the files are prepared, you can retrieve the download information for each file.
downloadFileInfo = downloadFileService.get(downloadSessionId,
downloadFileInfo.getName());
try {
URI downloadUri = downloadFileInfo.getDownloadEndpoint().getUri();
String downloadUrl = downloadUri.toURL().toString();
// Run an HTTP GET request and pass the download endpoints of the files.
HttpClient httpClient = new HttpClient(true);
InputStream inputStream = httpClient.downloadFile(downloadUrl);
String fileNameDownload = downloadFileInfo.getName();
File tmpDir = new java.io.File("tmp");
tmpDir.mkdir();
String fullPath = tmpDir.getAbsolutePath() +
System.getProperty("file.separator") + fileNameDownload;
Python Example of Downloading Files from a Library Item to Your Local System
This example uses the code in the cls_api_helper.py sample file.
This example uses the steps that are described in the Download Files to a Local System from a
Library Item procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
# 2 - Access the File service and retrieve the files you want to export.
download_session_file_stub = download_session_client.File(my_stub_config)
file_infos = download_session_file_stub.list(download_session_id)
for file_info in file_infos :
download_session_file_stub.prepare(download_session_id, file_info.name)
Synchronized on demand If the subscribed library is synchronized on demand, you can use the
sync method on the SubscribedItem service and pass as arguments
the library item ID and true. When you perform the task, both the
item metadata and the content are synchronized. To synchronize
only the metadata of the item, pass the library ID and false as
arguments to the method.
Not synchronized on demand If the subscribed library is not synchronized on demand, you can
use the sync method on the SubscribedItem service and pass as
argument the item ID. In this case, the content of the item is always
synchronized and the Boolean value is ignored when the call is run.
Synchronized automatically If the subscribed library is synchronized automatically, you can also
use the sync method to force the synchronization of an item. Method
execution depends on whether the subscribed library is synchronized
on demand.
If you create a subscribed library with the option to synchronize library content on demand, only
the metadata for the library items is stored. When you want to use the items in the library, you
must force synchronization on the items to download their content. When you no longer need
the files in an item, you can remove the cached content of the library item and free storage
space. To achieve this task use the evict function of the SubscribedItem object.
To remove a library item from a library, you can call the delete method on the Item object and
pass the library item ID as an argument. The item content is asynchronously removed from the
storage.
You cannot remove items from a subscribed library. If you remove an item from a local library,
the item is removed from the subscribed library when you perform a synchronization task on the
subscribed library item.
Open Virtualization Format (OVF) is an industry standard that describes metadata about a virtual
machine image in an XML format. An OVF package includes an XML descriptor file and optionally
disk images, resource files (such as ISO files), manifest files, and certificate files.
An OVA package is a single file that contains all OVF package files in an archived form. After
you upload an OVA package to a content library, the OVA file is converted to the standard OVF
package.
When you try to upload signed content to a content library, you might receive preview warnings.
Signed content can be either OVF or OVA packages that contain manifest and certificate files. If
you do not respond to the preview warnings, the upload fails. To complete an upload operation
successfully, you must ignore any preview warnings by using the WarningBehavior class.
With the vSphere Automation API, you can use the OVF package in a content library to deploy
virtual machines and vApps on hosts, resource pools, and clusters. You can also use the API to
create OVF packages in content libraries from vApps and virtual machines on hosts, resource
pools, and clusters.
When you create library items to store OVF packages, you must set the item type to ovf. To
comply with the specific standards of the OVF packages, the vSphere Automation API provides
the LibraryItem class.
In case you want to upload an OVF package, the location of the content determines whether you
can pull the content from a URL or push the content directly to a content library. For information
about uploading content to library items, see Upload a File from a Local System to a Library Item
and Upload a File from a URL to a Library Item.
To download the files that are included in an OVF or OVA package to your local file system, use
the DownloadSession interface. For more information, see Download Files to a Local System from
a Library Item .
Note If you try to upload a signed OVF package and it returns preview warnings, you must
ignore the preview warnings to complete the upload.
Prerequisites
n Create a new local content library or retrieve the desired existing content library.
n Required privileges: Content library.Add library item and Content library.Update files on the
library.
Procedure
3 Create an AddSpec object to describe the properties and the upload location of the OVF
descriptor file or of the OVA package file.
All files that are included in the OVF package are automatically uploaded.
This example uses the steps that are described in the Upload an OVF or an OVA Package from a
URL to a Library Item procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
Upload an OVF or OVA Package from a Local File System to a Library Item
You can upload an OVF or OVA package from a local file system. This procedure describes how
to use the AddSpec object after you have created a library item and initiated an update session.
Note If you try to upload a signed OVF package and it returns preview warnings, you must
ignore the preview warnings to complete the upload.
Prerequisites
n Create a new local content library or retrieve the desired existing content library.
n Required privileges: Content library.Add library item and Content library.Update files on the
library.
Procedure
3 Create an AddSpec object to describe the properties and the upload locations of the OVF
descriptor file or of the OVA package file.
5 (Optional) Create an AddSpec object for each VMDK file included in the OVF package.
If you upload an OVF package and it has a VMDK file included, you must repeat steps 5 and
6. If you are uploading a signed OVF package, steps 5 and 6 must also be repeated for the
manifest and certificate files included in the OVF package.
This example uses the steps that are described in the Upload an OVF or OVA Package from a
Local File System to a Library Item procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
# 2 - 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')
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
n Verify that you have administrative privileges on your vCenter Server instance.
n Verify that you created a vSphere Automation session to your vCenter Server.
n 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.
2 Get the ID of the datastore on which you want to store the VM template files.
3 Get the ID of the virtual machine that you want to save as a VM template.
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.
You can use the LibraryItems.CreatePlacementSpec class. To specify the host, resource
pool, cluster, and folder, you must use their IDs.
c 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.
d Include the placement and storage specifications in the library item specification.
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
n 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>.
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)
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_spec.name = self.item_name
create_spec.placement =
VmtxLibraryItem.CreatePlacementSpec(resource_pool=resource_pool_id)
Procedure
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.
...
createTarget.setLibraryId(myLibraryId);
}else {
System.out.println("Capture failed.");
}
if (result.getError() != null) {
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.
...
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))
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
n Verify that you have administrative privileges on your vCenter Server instance.
n Verify that you created a vSphere Automation session to your vCenter Server instance.
Procedure
2 Get the ID of the host on which you want to deploy the virtual machine.
3 Get the ID of the resource pool to which you want to add your virtual machine.
4 Get the ID of the VIRTUAL_MACHINE folder to which you want to add your virtual machine.
5 Get the ID of the datastore on which you want to store log, configuration, and disk files of the
virtual machine.
b 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.
c 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.
d (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.
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.
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)
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
Procedure
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.
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.
...
// 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);
result.getResourceId().getType(),
result.getResourceId().getId());
if (result.getSucceeded() == true) {
System.out.println("Resource instantiated.");
} else {
System.out.println("Instantiation failed.");
}
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.
...
Starting with vSphere 6.5, the vSphere Automation APIs provide programmatic access to
creating and managing vSphere tags in your vSphere inventory.
For example, if you want to tag your virtual machines by guest operating system type, you can
create a category called operating system. You can specify that it applies to virtual machines
only and that only a single tag can be applied to a virtual machines at any time. This category can
include the following tags: Windows, Linux, and Mac OS.
n Updating a Tag
n If multiple on-premises vCenter Server instances are configured to use Enhanced Linked
Mode, tags and tag categories are replicated across all these vCenter Server instances.
n When you use Hybrid Linked Mode, tags and tag categories are maintained across your
linked domain. That means the on-premises SDDC and the VMware Cloud on AWS SDDC
share tags and tag attributes. For more information about Hybrid Linked Mode, see "Hybrid
Linked Mode" in the VMware Cloud on AWS Product Documentation.
n name
n description
You can associate tags with both vSphere API managed objects and VMware vSphere
Automation API resources.
This example is based on the information that is provided in Creating a Tag Category.
The category create() function returns an identifier that you use when you create a tag for
that category. The empty set for the associable types indicates that any object type can be
associated with a tag in this category.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example is based on the information that is provided in Creating a Tag Category.
The category create() function returns an identifier that you use when you create a tag for
that category. The empty set for the associable types indicates that any object type can be
associated with a tag in this category.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
category_stub = tagging_client.Category(my_stub_config)
Creating a Tag
After you create a tag category, you can create tags within that category
n name
n description
n category ID
This example creates a tag specification and then uses it to create the tag. The tag specification
references the category identifier that was returned from the category create operation. Use the
returned tag identifier for subsequent operations on the tag.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example creates a tag specification and then uses it to create the tag. The tag specification
references the category identifier that was returned from the category create operation. Use the
returned tag identifier for subsequent operations on the tag.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
Tag associations are local to a vCenter Server instance. When you request a list of tag
associations from a vCenter Server system, it enumerates only the associations that it has stored.
When you associate a tag with an object, the object's type must match one of the associable
types specified for the category to which the tag belongs.
Procedure
This example uses the steps that are described in the Assign the Tag to a Content Library
procedure.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example uses the steps that are described in the Assign the Tag to 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.
...
This procedure describes the steps for applying tag a to a cluster object in your inventory.
Prerequisites
To get the managed object identifier of the ClusterComputeResource, you must access vCenter
Server by using the vSphere Web Services API. For more information about how to access Web
Services, see Create a Web Services Session.
Procedure
The dynamic identifier includes the type and ID of the managed object reference.
This example is based on the information that is provided in Assign a Tag to a Cluster.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example is based on the information that is provided in Assign a Tag to a Cluster.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
Updating a Tag
To update a tag, you must create an update spec for the tag. In the update spec, you set
values for the fields to be changed, and omit values for the other fields. When you do an update
operation using the update spec, only the fields that contain values are changed.
For example, you might use a timestamp in a tag description to identify a resource's last
reconfiguration. After reconfiguring the resource, you update the tag description to contain the
current time.
This example adds timestamp in a tag description to identify when a resource was last
reconfigured. The tag description is updated with the timestamp after the resources is
reconfigured.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
...
This example adds timestamp in a tag description to identify when a resource was last
reconfigured. The tag description is updated with the timestamp after the resources is
reconfigured.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
tag_stub = tagging_client.Tag(my_stub_config
Procedure
2 Retrieve the object ID of the host you want the virtual machine to run on.
Note The host should be different from the host the virtual machine is already running on.
This example uses the steps that are described in the Create a Compute Policy procedure.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
def run(self):
# Get the virtual machine and power it off.
self.vm_id = get_vm(self.client, self.vm_name)
self.vm_info = self.client.vcenter.VM.get(self.vm_id)
if not self.vm_info:
raise ValueError("Virtual machine {} not found".format(
self.vm_name))
else:
if self.vm_info.power_state == Power.State.POWERED_ON:
self.client.vcenter.vm.Power.stop(self.vm_id)
elif self.vm_info.power_state == Power.State.SUSPENDED:
self.client.vcenter.vm.Power.start(self.vm_id)
self.client.vcenter.vm.Power.stop(self.vm_id)
if not vm_tag:
raise ValueError("Provided tag(s) not found")
...
You can use the vSphere Automation to automate the enabling and disabling of vSphere with
Tanzu on a vSphere cluster, creating and managing namespaces.
The information in this chapter is intended for vSphere administrators who want to use the
vSphere Automation APIs to configure their environment to run Kubernetes workloads in
vSphere. To take fully advantage of these vSphere Automation APIs, you must have basic
knowledge about the Kubernetes technology and containers.
For more information about how to configure and manage vSphere with Tanzu through the
vSphere Client, see the Installing and Configuring vSphere with Tanzu and vSphere with Tanzu
Configuration and Management documentation.
This chapter includes the following topics:
Supervisor A vSphere cluster that has the vSphere with Tanzu enabled.
vSphere Pod A virtual machine with a small footprint that runs one or
more Linux containers. A vSphere Pod is equivalent to a
Kubernetes pod. vSphere Pods are compatible with the
Open Container Initiative (OCI) and can run OCI compatible
containers regardless the operating system.
Kubernetes Workload Workloads are applications that are deployed in one of the
following ways:
n As containers running inside vSphere Pods.
n Workloads provisioned through the VM service.
n Tanzu Kubernetes Gridclusters deployed by using the
Tanzu Kubernetes Grid.
n Applications running inside the Tanzu Kubernetes Grid
clusters.
Supervisor control plane vSphere with Tanzu creates a Kubernetes control plane
directly on the hypervisor layer. The control plane manages
the worker nodes and the vSphere Pods in the Supervisor.
Supervisor worker nodes ESXi hosts that are part of a Supervisor are considered as
worker nodes. You run your Kubernetes workloads on the
worker nodes.
Container Runtime Executive (CRX) CRX is an isolated Linux execution environment similar to a VM
that works together with ESXi.
Term Description
The vSphere with Tanzu API consists of two packages, namespace_management and namespaces.
In the namespace_management package, you can find APIs for enabling a vSphere cluster with
vSphere with Tanzu, configuring the network and storage policies of the Supervisor, upgrading a
cluster to the desired version of vSphere with Tanzu, and so on. In the namespaces package, you
can find APIs for creating, configuring, and deleting a vSphere Namespace, and also for setting
the necessary permissions for accessing the namespace.
Figure 11-1. Services and Components Involved in Using vSphere with Tanzu
vSphere with
Tanzu Services
Virtual Virtual
Machine Machine
Clusters Image Class
Pod
Virtual Machine
Instances
vSphere vSphere vSphere vSphere vSphere Tanzu vSphere
Pod Pod Pod Pod Pod Kubernetes Cluster Pod
Load
Balancers Create and
Enable Virtual Virtual Virtual Virtual
Manage a
vSphere Machine Machine Machine Machine
Supervisor
with Tanzu Class Class Class Class
Virtual Namespace
on a vSphere
Cluster Machine
Classes Supervisor Namespace / Supervisor Namespace / Supervisor Namespace / Supervisor Namespace /
Instances Instances Instances Instances
Namespace
Self Service
vSphere
Admin Virtual Machine Virtual Machine
Classes Service Classes Service
Create Namespace
and Manage Templates
Create a Supervisor Cluster / Clusters Supervisor Cluster / Clusters
Kubernetes
Supervisor
Clusters
Cluster
Access
Service
vSphere Cluster
Postgres DB
vCenter Server
The vSphere Kubernetes Services component runs on vCenter Server and communicates the
vSphere admin requests to the Supervisor control plane. The component comprises of several
services which vSphere Automation endpoints you can use to enable vSphere with Tanzu on a
vSphere cluster and create Kubernetes workloads.
You can use the Cluster Compatibility service to query a vCenter Server instance about the
available clusters that meet the requirements for enabling vSphere with Tanzu.
You can use the Clusters service to enable or disable vSphere with Tanzu on a cluster. You can
also reconfigure the settings of a Supervisor.
You can use the Instances service to create, edit, and delete a vSphere Namespace from a
Supervisor. You can also change all or some of the settings of an existing namespace.
Starting with vSphere 7.0 Update 1, a Supervisor backed by a vSphere Distributed Switch uses
the HAProxy load balancer to provide connectivity to DevOps and external service. The Load
Balancer service represents the user provisioned load balancers.
Starting with vSphere 7.0 Update 2a, vSphere administrators can use the VM Service
functionality to enable DevOps engineers to deploy and run VMs and containers in one shared
Kubernetes environment through a single Kubernetes native interface. Use the vSphere with
Tanzu APIs to define VM Classes and content libraries to allocate resources to virtual machines
provisioned by DevOps engineers.
As of vSphere 7.0 Update 2a, vSphere administrators can also configure a vSphere Namespace
as a template on a cluster. Then the DevOps engineers can use it to self-service the creation of
vSphere Namespaces and deploy workloads within them.
You can enable a vSphere cluster to manage Kubernetes workload objects, only after you enable
vSphere DRS in a fully automated mode and enable HA on the cluster.
Before you enable a vSphere with Tanzu on a vSphere cluster, you must prepare your
environment to meet the specific networking, storage, and infrastructure requirements. See the
Installing and Configuring vSphere with Tanzu documentation.
For more information about how to configure the storage settings to meet the requirements of
vSphere with Tanzu, see Creating Storage Policies for vSphere with Tanzu.
For more information about how to configure the networking settings for Supervisors that are
configured with the VMware NSX-T™ Data Center as the networking stack, see Configuring NSX
for vSphere with Tanzu.
Starting with vSphere 7.0 Update 1, you can enable a Supervisor with vSphere networking or
NSX-T Data Center, to provide connectivity between control planes, services, and workloads.
A Supervisor that is configured with vSphere networking uses a vSphere Distributed Switch to
provide connectivity to Kubernetes workloads and control planes. The cluster also requires a
third-party load balancer that provides connectivity to DevOps users and external services. You
can install in your vSphere environment the HAProxy load balancer implementation that VMware
provides. See Configuring the vSphere Networking Stack for vSphere with Tanzu and Installing
and Configuring the HAProxy Load Balancer.
Staring with vSphere 7.0 Update 2, if you are using vSphere networking, you can use the
®
VMware NSX Advanced Load Balancer™ to support Tanzu Kubernetes clusters provisioned
by the Tanzu Kubernetes Grid. See Using the NSX Advanced Load Balancer with vSphere
Networking.
To understand how vSphere with Tanzu uses persistent storage, refer to the vSphere with Tanzu
Concepts and Planning and vSphere Storage documentations.
Use the vSphere Automation APIs to retrieve the default storage policy of a specific datastore
by calling the get(datastore_ID) function of the com.vmware.vcenter.datastore.DefaultPolicy
service. You can also retrieve commonly used information about the storage policies available in
the vCenter Server instance by calling the list() function of the Policies service.
You can use the storage policies retrieved through the vSphere Automation APIs to perform the
following tasks:
n Assign the storage policies to the Supervisor. The storage policies set within the Supervisor
enable specification ensure that the Supervisor control plane, the ephemeral disks of all
vSphere Pods, and the container images are placed on the datastores that the policies
represent. See Configuring NSX for vSphere with Tanzu.
n Assign the storage policies to the vSphere Namespace. The storage policies associated with
a namespace determine which datastores the namespace can access and use for persistent
volumes for the vSphere Pod and the pods inside a Tanzu Kubernetes cluster. See Create a
vSphere Namespace.
In vSphere 7.0 Update 3, only Tanzu Kubernetes clusters support persistent volumes in
ReadWriteMany mode. When you enable file volume support for vSphere with Tanzu, be aware
of the potential security weaknesses:
n The volumes are mounted without encryption. The unencrypted data might be accessed
while the data transits the network.
n Access Control List (ACL) is used for the file shares to isolate file share access within a
supervisor namespace. It might have risk of IP spoofing.
n Make sure the vSAN File Services is routable from the Workload network and there is no NAT
between the Workload network and vSAN File Services IP addresses.
n Use common DNS server for vSAN File Services and the vSphere cluster.
n If your vSphere with Tanzu has NSX networking, use the SNAT IP of the Supervisor
namespace and the SNAT IP of the Tanzu Kubernetes cluster for ACL configuration.
n If you have vSphere with Tanzu with vSphere Distributed Switch (VDS) networking, use the
Tanzu Kubernetes cluster VM IP or the IP of the Supervisor namespace for ACL configuration.
Before you activate the file volume support on a Supervisor, you must set up a vSAN cluster
with enabled vSAN File Service. To configure a vSAN cluster with enabled vSAN File Service
in the vSphere Client, see the Configure File Services topic in the Administering VMware vSAN
documentation. For more information about how to programmatically achieve this task, see the
vSAN SDKs Programming Guide documentation.
You activate the ReadWriteMany support on a cluster when you enable vSphere with Tanzu
on it, or reconfigure an existing Supervisor. See Enable vSphere with Tanzu on a Cluster with
NSX as the Networking Stack, Enable vSphere with Tanzu on a Cluster with the vSphere
Networking Stack, and Reconfiguring a Supervisor. Pass the list of vSAN clusters to be used
for provisioning file volumes by using the setCnsFileConfig(CNSFileConfig cnsFileConfig)Java
method . Currently, you can use only the current vSphere cluster for provisioning file volumes if it
is a vSAN cluster with enabled vSAN File Service.
To deactivate the persistent volumes support on a Supervisor, pass an empty list when you
set the Cloud Native Storage persistent storage support for the cluster. After that existing
ReadWriteMany persistent volumes provisioned in the cluster remain unaffected and usable.
Supervisor Networking
You can enable a Supervisor with vSphere networking or NSX to provision connectivity to
Kubernetes control planes, services, and workloads.
A Supervisor that uses the vSphere networking stack is backed by a vSphere Distributed Switch
and requires a load balancer to provide connectivity to DevOps users and external services. The
NSX Advanced Load Balancer and the HAProxy load balancers are supported for vSphere 7.0
Update 2.
A Supervisor that is configured with NSX, uses the software-based networks of the solution and
an NSX Edge load balancer to provide connectivity to external services and DevOps users.
Follow the instructions for installing and configuring the NSX for managing Kubernetes workloads
documented in the Installing and Configuring vSphere with Tanzu guide.
First, you need to create a vSphere Distributed Switch and a distributed port group for each
NSX Edge uplink. To automate this step, use the Web Services APIs as described in the vSphere
Web Services SDK Programming Guide. Then, you can use the NSX REST APIs to add a compute
manager, create transport zones, and perform other steps required for configuring the NSX for
vSphere with Tanzu.
Workload networks provide connectivity to the nodes of Tanzu Kubernetes clusters and to the
Supervisor control planes. The workload network that provides connectivity to Supervisor control
planes is called primary workload network. Each Supervisor must have one primary workload
network represented by a distributed port group.
The Supervisor control planes on the cluster use three IP addresses from the IP address range
that is assigned to the primary workload network. Each node of a Tanzu Kubernetes cluster has a
separate IP address assigned from the address range of the workload network that is configured
with the namespace where the Tanzu Kubernetes cluster runs.
To create a vSphere Distributed Switch and port groups for configuring the vSphere networking
stack of a Supervisor, you can use the vSphere Web Services APIs as described in the vSphere
Web Services SDK Programming Guide documentation. When you create a distributed virtual
switch, vCenter Server automatically creates one distributed virtual port group. You can use this
port group as the primary workload network and use it to handle the traffic for the Supervisor
control planes. Then you can create as many distributed port groups for the workload networks
as your topology requires. For a topology with one isolated workload network, create one
distributed port group that you will use as a network for all namespaces on the Supervisor.
For a topology with isolated networks for each vSphere Namespace, create the same number of
distributed port groups as the number of namespaces.
To list all workload networks available for a Supervisor and retrieve information
about the configuration of a specific workload network, use the Networks
service from the vSphere Automation APIs. To associate a vSphere Distributed
port group to a workload network, set the necessary information through the
If you want to retrieve a list of the distributed switches compatible with vSphere with Tanzu on a
vCenter Server system, use the DistributedSwitchCompatibility service and filter the available
switches by using VSPHERE_NETWORK as the networking provider.
If you use the vSphere networking stack in your vSphere with Tanzu environment, you need to
supply your own load balancer. You can use the open source implementation of the HAProxy
load balancer that VMware provides.
For more information about the prerequisites for installation and the deployment procedure
through the vSphere Client, see the Installing and Configuring vSphere with Tanzu
documentation.
You can use the vSphere Automation APIs to install and configure the HAProxy load balancer.
You can download the latest version of the HAProxy OVA file from the VMware-HAProxy site to
a content library item. For more information about how to achieve this task, see Upload an OVF
or OVA Package from a Local File System to a Library Item . Then you can create a new VM from
the OVA template in the content library as described in Deploy a Virtual Machine or vApp from
an OVF Template in a Content Library.
To configure the HAProxy load balancer, call the set(String cluster, String
id, LoadBalancersTypes.SetSpec spec) and pass the configuration through the
LoadBalancersTypes.SetSpec object. The load balancer specification takes as a setting a
LoadBalancers.HAProxyConfigCreateSpec instance that captures the runtime configuration of the
HAProxy load balancer. You must set the following configuration parameters to the HAProxy
load balancer configuration specification:
Parameter Description
setUsername(String username) The administrator user name that is configured with the
HAProxy OVA file and is used to authenticate to the
HAProxy Data Plane API server.
Parameter Description
For more information about how to install and configure the NSX Advanced Load
Balancerthrough the vSphere Client, see the Installing and Configuring vSphere with Tanzu
documentation.
You can use the vSphere Automation APIs to deploy the Avi Controller on your vSphere
Management network. You can upload the latest version of the NSX Advanced Load Balancer
to a library item from your local file system or from a URL. For more information about how to
achieve this task, see Upload an OVF or OVA Package from a Local File System to a Library
Item . Then you can deploy the Controller VM on your vSphere Management network from the
OVA template in the content library as described in Deploy a Virtual Machine or vApp from an
OVF Template in a Content Library.
Parameter Description
setServer(LoadBalancersTypes.Server server) The address of the Avi Controller that is used to configure
virtual services.
setUsername(java.lang.String username) The administrator user name that is used for accessing the
Controller VM of the NSX Advanced Load Balancer.
To enable a vSphere cluster for Kubernetes workload management, you use the services under
the namespace_management package.
Prerequisites
n Verify that your environment meets the system requirements for enabling vSphere with
Tanzu on the cluster. For more information about the requirements, see the vSphere with
Tanzu Concepts and Planning documentation.
n Verify that the NSX is installed and configured. See Configuring NSX for vSphere with Tanzu.
n Create storage policies for the placement of pod ephemeral disks, container images, and
Supervisor control plane cache.
n Verify that DRS is enabled in fully automated mode and HA is also enabled on the cluster.
n Configure shared storage for the cluster. Shared storage is required for vSphere DRS, HA,
and storing persistent volumes of containers.
n Verify that the user who you use to access the vSphere Automation services has the Modify
cluster-wide configuration privilege on the cluster.
n Create a subscribed content library on the vCenter Server system to accommodate the VM
image that is used for creating the nodes of the Tanzu Kubernetes clusters.
Procedure
1 Retrieve the IDs of the tag-based storage policies that you configured for vSphere with
Tanzu.
Use the Policies service to retrieve a list of all storage policies and then filter the policies to
get the IDs of the policies that you configured for the Supervisor.
2 Retrieve the IDs of the vSphere Distributed Switch and the NSX Edge cluster that you created
when configuring the NSX for vSphere with Tanzu.
3 Retrieve the ID of the port group for the management network that you configured for the
management traffic.
Use the Networks service to list the visible networks available on the vCenter Server instance
that match some criteria and then retrieve the ID of the management network you previously
configured.
You must specify the following required parameters of the enable specification:
n Storage policies settings and file volume support. The storage policy you set for each of
the following parameters ensures that the respective object is placed on the datastore
referenced in the storage policy. You can use the same or different storage policy for the
different inventory objects.
Parameter Description
n Management network settings. Configure the management traffic settings for the
Supervisor control plane.
Parameter Description
Parameter Description
n Workload network settings. Configure the settings for the networks for the namespaces.
The namespace network settings provide connectivity to vSphere Pods and namespaces
created in the Supervisor.
Parameter Description
n setClusterDistributedSwitch(java.lang.String
clusterDistributedSwitch) - The vSphere
Distributed Switch that handles overlay networking
for the Supervisor.
n setNsxEdgeCluster(java.lang.String
nsxEdgeCluster)- The NSX Edge cluster that
has tier-0 gateway that you want to use for
namespace networking.
n setNsxTier0Gateway(java.lang.String
nsxTier0Gateway) - The tier-0 gateway that is
associated with the cluster tier-1gateway. You
can retrieve a list of NSXTier0Gateway objects
associated with a particular vSphere Distributed
Switch and determine the ID of the tier-0 gateway
you want to set.
n setNamespaceSubnetPrefix(java.lang.Long
namespaceSubnetPrefix)- The subnet prefix that
defines the size of the subnet reserved for
namespaces segments. Default is 28.
n setRoutedMode(java.lang.Boolean routedMode) -
The NAT mode of the workload network. If set to
false:
Parameter Description
setServiceCidr(Ipv4Cidr serviceCidr) Specify the CIDR block from which the IP addresses
for Kubernetes services are allocated. The IP range
must not overlap with the ranges of the vSphere Pods,
ingress, egress, or other services running in the data
center.
For the Kubernetes services and the vSphere Pods,
you can use the default values which are based on the
cluster size that you specify.
n Supervisor size. You must set a size to the Supervisor which affects the resources
allocated to the Kubernetes infrastructure. The cluster size also determines default
maximum values for the IP addresses ranges for the vSphere Pods and Kubernetes
services running in the cluster. You can use the ClusterSizeInfo.get() calls to retrieve
information about the default values associated with each cluster size.
n Optional. Associate the Supervisor with the subscribed content library that you created
for provisioning Tanzu Kubernetes clusters. See Creating, Securing, and Synchronizing
Content Libraries for Tanzu Kubernetes Releases.
5 Enable vSphere with Tanzu on a specific cluster by passing the cluster enable specification to
the Clusters service.
Results
A task runs on vCenter Server for turning the cluster into a Supervisor. Once the task completes,
Kubernetes control plane nodes are created on the hosts that are part of the cluster enabled with
vSphere with Tanzu. Now you can create vSphere Namespaces.
What to do next
Create and configure namespaces on the Supervisor. See Create a vSphere Namespace.
The following code snippet is part of the EnableSupervisorCluster.java sample. Some parts of
the original code sample are omitted to save space. You can view the complete and up-to-date
version of this sample in the vsphere-automation-sdk-java VMware repository at GitHub.
(...)
@Override
protected void run() throws Exception {
this.ppClusterService.enable(clusterId, spec);
System.out.println("Invocation is successful for enabling vSphere supervisor cluster,
check H5C");
}
(...)
To enable a cluster configured with the vSphere networking stack for Kubernetes workloads
management, you must use the services under the namespace_management package.
Prerequisites
n Verify that your environment meets the system requirements for enabling vSphere with
Tanzu on the cluster. For more information about the requirements, see the documentation.
n Verify that DRS is enabled in fully automated mode and HA is also enabled on the cluster.
n Configure shared storage for the cluster. Shared storage is required for vSphere DRS, HA,
and storing persistent volumes of containers.
n Create a subscribed content library on the vCenter Server system to accommodate the VM
image that is used for creating nodes of Tanzu Kubernetes clusters. See Creating, Securing,
and Synchronizing Content Libraries for Tanzu Kubernetes Releases.
n Add all hosts from the cluster to a vSphere Distributed Switch and create port groups for
workload networks. See Configuring the vSphere Networking Stack for vSphere with Tanzu.
n Configure an HAProxy load balancer instance that is routable to the vSphere Distributed
Switch that is connected to the hosts from the vSphere cluster.
n Verify that the user who you use to access the vSphere Automation services has the
Namespaces.Manage privilege on the cluster.
Procedure
1 Retrieve the ID of the cluster which hosts were added to the vSphere Distributed Switch.
Use the ClusterCompatibility service to filter the clusters by using their network providers.
To retrieve a list of all clusters in the vCenter Server system which are configured with
the vSphere networking stack, set the network provider in the filter specification to
VSPHERE_NETWORK.
2 Retrieve the IDs of the tag-based storage policies that you configured for vSphere with
Tanzu.
Use the Policies service to retrieve a list of all storage policies and then filter the policies to
get the IDs of the policies that you configured for the Supervisor.
3 Retrieve the ID of the port group for the management network that you configured for the
management traffic.
To list the visible networks available on the vCenter Server instance that match some criteria
and then retrieve the ID of the management network you previously configured, use the
Networks service.
4 Create a Supervisor enable specification and define the parameters of the Supervisor that
you want to enable.
You must specify the following required parameters of the enable specification:
n Supervisor size. You must set a size to the Supervisor which affects the resources
allocated to the Kubernetes infrastructure. The cluster size also determines default
maximum values for the IP addresses ranges for the vSphere Pod and Kubernetes
services running in the cluster. You can use the ClusterSizeInfo.get() call to retrieve
information about the default values associated with each cluster size.
n Storage policy settings and file volume support. To specify the ID of the storage policy
that you created to control the placement of the Supervisor control plane cache, use the
setMasterStoragePolicy(java.lang.String masterStoragePolicy) method. Optionally,
you can activate the file volume support by using the setCnsFileConfig(CNSFileConfig
cnsFileConfig) method. See Enabling ReadWriteMany Support.
Parameter Description
setProvider(LoadBalancersTypes.Provider The type of the load balancer that you want to use. In
provider) vSphere 7.0 Update 2, you can choose between the
HAProxy load balancer and the NSX Advanced Load
Balancer. Pass as a value to this parameter one of the
following constants: HA_PROXY or AVI.
Parameter Description
n Management network settings. Configure the network parameters for the Kubernetes
control planes.
Parameter Description
n Workload network settings. Configure the settings for the network that will handle the
networking traffic for Kubernetes workloads running on the Supervisor.
Parameter Description
setServiceCidr(Ipv4Cidr serviceCidr) Specify the CIDR block from which the IP addresses
for Kubernetes services are allocated. The IP range
must not overlap with the ranges of the vSphere Pods,
ingress, egress, or other services running in the data
center.
For the Kubernetes services and the vSphere Pods,
you can use the default values which are based on the
cluster size that you specify.
n Content library settings. Add the subscribed content library that contains the VM images
for deploying the nodes of Tanzu Kubernetes clusters. See Creating, Securing, and
Synchronizing Content Libraries for Tanzu Kubernetes Releases.
5 Enable the Supervisor by passing the enable specification to the Clusters service.
Results
A task runs on vCenter Server for enabling vSphere with Tanzu on the cluster. Once the task
completes, three Kubernetes control planes are created on the hosts that are part of the cluster.
What to do next
Upgrading a Supervisor
You can use the vSphere with Tanzu APIs to upgrade a single or a group of clusters to a specific
version.
vSphere with Tanzu supports rolling upgrades through the vSphere Automation APIs for
Supervisors and for the infrastructure supporting these clusters. This model ensures that there is
minimal downtime for the cluster workloads during the upgrade process.
To retrieve a list of all available vSphere with Tanzu upgrade versions for a specific vCenter
Server system, use the Cluster Available Versions service. You can get information about the
release version, name, description, release date, and release notes for each available upgrade.
You must use the Software Clusters service for upgrading a Supervisor. You can retrieve upgrade
information about all Supervisors enabled on a vCenter Server system by using the list()
Java method . You receive a list of basic upgrade-related information for each cluster, such
as the current software version, the date of the last successful upgrade, the upgrade status of
the cluster, and so on. In case some of the clusters are in the process of upgrading, you can
retrieve also information about their desired upgrade version. If you want to view a more detailed
upgrade-related information about a cluster, you must use the get(cluster_ID) method.
After you view the details about the upgrade versions that you can apply on a single or multiple
Supervisors, you can create upgrade specifications that define the versions you want to upgrade
to. When you upgrade a batch of Supervisor and for some reason one of the clusters fails
to upgrade, you receive information about the pre-check exceptions that led to that cluster
upgrade failure.
The following code snippet is part of the UpgradeSupervisorCluster.java sample. Some parts of
the original code sample are omitted to save space. You can view the complete and up-to-date
version of this sample in the vsphere-automation-sdk-java VMware repository at GitHub.
@Override
protected void run() throws Exception {
To monitor the status of the enable and upgrade Supervisor operations, use the
ClustersTypes.Info instance and query the Kubernetes and configuration status of the cluster.
Track the status every two minutes or so, until you receive READY for getKubernetesStatus() and
RUNNING for getConfigStatus(). These statuses indicate that the Supervisor reached the desired
configuration status and is ready for running Kubernetes workloads.
Reconfiguring a Supervisor
You can change some or all the predefined settings of a Supervisor through the vSphere
AutomationAPIs.
To update only some of the Supervisor settings, you must create an instance of UpdateSpec and
pass it to the update(cluster_ID, update_spec) method. To reconfigure entirely the Supervisor,
you must create an instance of SetSpec and pass it to the set(cluster_ID, set_spec) method.
The settings you can configure with the UpdateSpec and SetSpec specifications are the same as
the ones that you used for enabling the Supervisor. For example, you can change the storage
settings on the Supervisor. Note that the changes that you make to the storage settings after the
initial cluster configuration, apply only to the newly created Supervisor control planes.
Disabling a Supervisor
You can programmatically disable vSphere with Tanzu on a vSphere cluster by using the vSphere
Automation APIs.
When you deactivate a Supervisor, the vSphere Kubernetes Service forcefully deletes from
the cluster all objects and configurations part of the Kubernetes infrastructure. To deactivate
Kubernetes workloads on a cluster, call the disable(String cluster) operation of the Clusters
service and pass as parameter the ID of the cluster on which you want to deactivate Kubernetes.
A Tanzu Kubernetes release provides the VMware Kubernetes distribution which can be used
with Tanzu Kubernetes clusters. Each Tanzu Kubernetes release is distributed as an OVA
package. The Tanzu Kubernetes Grid uses the OVA package to deploy the virtual machine nodes
for Tanzu Kubernetes clusters.
A Tanzu Kubernetes release is supported on Photon OS. The virtual machine nodes that are
built from the OVA package have a 16 GB disk size. You specify the CPU and RAM resource
reservations when you use a virtual machine class to size the Tanzu Kubernetes cluster.
Depending on your need for synchronization frequency and on the access to the published
content libraries storing the Tanzu Kubernetes releases, you can use two approaches for storing
Tanzu Kubernetes releases.
Note Starting with vSphere 7.0 Update 3, you can protect your content library by a security
policy. In such case, make sure that all library items are compliant. If a protected library includes a
mix of compliant and non-compliant library items, DevOps engineers are not able to retrieve the
list of VM images provided with the library.
When you create the subscription, you configure the synchronization mechanism for
downloading the content of the published library. You can select between on demand and
automatic download of the virtual machine image for the Tanzu Kubernetes cluster nodes. If
you choose to synchronize the subscribed library on demand, only the metadata for the library
content is updated and as a result storage space is saved. This approach is an important
consideration as more images containing different Kubernetes versions are published. However,
the first time you decide to use a new virtual machine image version, you have to wait for it to
download.
Starting with vSphere 7.0 Update3, you can secure a subscribed content library. The Content
Library service verifies the library signing certificate during the synchronization process. If the
certificate verification fails, only the library metadata is synchronized and the library content
is not downloaded. For more information how to apply a security policy when you update a
subscribed content library, see Editing the Settings of a Content Library.
You associate the subscribed content library with the Supervisor on which you want to create
a Tanzu Kubernetes cluster, when you first enable vSphere with Tanzu on a cluster. See Enable
vSphere with Tanzu on a Cluster with NSX as the Networking Stack.
The size of the content library can grow over time as new Kubernetes versions and images are
published. If the underlying storage runs out of space, you will need to move to a new subscribed
content library. After you create a new subscribed content library that has sufficient capacity
for the target cluster, update the library association of the Supervisor. See Reconfiguring a
Supervisor.
Starting with vSphere 7.0 Update3, you can secure a local content library. The Content Library
service verifies the library signing certificate during the synchronization process. If the certificate
verification fails, only the library metadata is synchronized and the library content is not
downloaded. For more information how to apply a security policy when you update a local
content library, see Editing the Settings of a Content Library.
You can find the latest versions of the Kubernetes distribution by navigating to the https://
wp-content.vmware.com/v2/latest URL. You must download the photon-ova.ovf and photon-
ova-disk1.vmdk for each distribution you want and then upload these files from your local file
system to your local content library. See Upload an OVF or OVA Package from a Local File
System to a Library Item .
Note Make sure that you use as a name for each library item the Photon image version
and the Kubernetes version from the directory where you downloaded the files. For example:
photon-3-k8s-v1.20.2---vmware.1-tkg.1.1d4f79a.
You can create a local content library and populate it with VM templates in OVF or OVA file
format, or other types of files. For more information and a sample of how to create a local
content library, see Create a Local Content Library.
You can also create a subscription to download the content of a published local content library
as described in the following topic: Subscribe to a Content Library.
Starting with vSphere 7.0 Update3, you can secure the content library. The Content Library
service verifies the library signing certificate during the synchronization process. If the certificate
verification fails, only the library metadata is synchronized and the library content is not
downloaded. For more information how to apply a security policy when you update a local or
subscribed content library, see Editing the Settings of a Content Library.
After you create the content library, you must populate it with content either from your local file
system or from a Web server. You must use only the VM images available on the VMware Cloud
Marketplace web site. For example, download or subscribe to VM Service Image for Ubuntu if
you want to enable a DevOps engineer to deploy a VM using this image. For more information
about the available ways to populate a content library with content, see Library Items.
You must give the DevOps engineers access to the VM templates stored in the content libraries,
so that they can use these templates to provision VMs through the VM Service functionality. To
give access, you must associate one or more content libraries to the namespace where the VM
Service is present. See Associating a Content Library with a Namespace and Virtual Machines in
vSphere with Tanzu.
You can add multiple content libraries to a namespace that has the VM Service enabled or the
same content library to several namespaces. You associate a content library to a namespace
when you create a new namespace, update or reconfigure an existing one.
To make the VM Service aware of the content libraries in your environment that the
DevOps engineers can use to self-service VMs, you must use a VMServiceSpec instance
and pass it to the namespace configuration. The instance contains a list of content
libraries that will be used by the VM Service. You can specify this list by calling the
setContentLibraries(java.util.Set<java.lang.String> contentLibraries) method of the VM
Service specification.
You can also associate one or more VM classes with the namespace. See Associating a VM Class
with a vSphere Namespace.
To create and configure a namespace, use the Instances service from the namespaces package.
You can configure the access control to the objects in a namespace by using the Access service.
Prerequisites
n Create users and groups for the DevOps engineers who will use the namespace. For more
information about how to create users and groups through the Web Services APIs, see the
vSphere Web Services SDK Programming Guide.
n Create storage policies for persistent storage used by the vSphere Pods and the pods inside
a Tanzu Kubernetes cluster.
n Create VM Classes and content libraries for DevOps provisioned VMs. See Create a VM Class
in vSphere with Tanzu and Creating and Managing Content Libraries for VM Provisioning in
vSphere with Tanzu.
Procedure
1 Retrieve the Supervisor ID by filtering the clusters available in the vCenter Server system.
2 Retrieve the ID of the storage policy that you configured for placement of the persistent
volumes from vSphere Pods and Tanzu Kubernetes clusters.
Parameter Description
setSubjectType(subjectType) Set the type of the user accounts that are associated
with the specific role for the namespace. You must select
between the USER and GROUP options.
setSubject(subject) Set the name of the user or group that have permissions
to access the namespace objects.
setRole(role) Set the role that is associated with the predefined set
of privileges that you want to grant the specific user or
group. You can select between the EDIT, VIEW and OWNER
roles.
The owner role is introduced in vSphere 7.0 Update 2a.
When a DevOps engineer creates a namespace in a self-
service manner, the Namespace Self-Service grants the
owner role to the namespace creator. See Self-Service
Namespace Management.
Parameter Description
Parameter Description
5 Create a namespace object on the Supervisor by using the namespace create specification.
What to do next
Share the namespace with DevOps engineers and provide them with the user or group
configured for accessing the namespace.
The following code snippet is part of the CreateNameSpace.java sample. Some parts of the
original code sample are omitted to save space. You can view the complete and up-to-date
version of this sample in the vsphere-automation-sdk-java VMware repository at GitHub.
(...)
@Override
protected void run() throws Exception {
} else{
accessList.setRole(AccessTypes.Role.VIEW);
}
accessList.setSubject( this.subjectName); //Default is Administrator
if(this.subjectType.equalsIgnoreCase("USER")) {
accessList.setSubjectType( AccessTypes.SubjectType.USER);
} else{
accessList.setSubjectType( AccessTypes.SubjectType.GROUP);
}
}
(...)
Note Before deleting a storage policy from vCenter Server or a vSphere Namespace, or
changing the storage policy assignment, make sure that no persistent volume claim with the
corresponding storage class runs in the namespace. Also, ensure that no Tanzu Kubernetes
cluster is using the storage class.
To patch a namespace configuration, create an UpdateSpec specification and set new values
only to the configuration settings that you want to change. The parameters of the update
specification are the same as the ones you configured during the namespace creation. When
you call the update operation, only the settings that you configured in the update specification
are applied, the other settings are left as they are.
To reconfigure a namespace entirely, you must create an instance of the SetSpec class. You can
change the description, access controls, storage settings, and resource limitations of the specific
namespace.
Use the Access service to retrieve information about the access control of the DevOps engineers
on a specific namespace. You can also set up or remove an access control for a specific user or
group on a specific namespace, and add another access control on the namespace. You set up
each access control to allow a user or group to access a namespace in a specific vCenter Server
system. You can grant access to a DevOps engineer to more than one namespace.
You must have the Namespaces.Configure. privilege to grant permissions to a user. You assign
the view and edit access role on the namespace for the user or group.
Starting with vSphere 7.0 Update 2а, you can also assign the owner role to a DevOps engineer.
These roles allow the user to deploy workloads, share the namespace with other DevOps
engineers, and delete it when it is no longer needed.
Starting with vSphere 7.0 Update 2a, the Namespace Self-Service feature is available in
vSphere with Tanzu. The service enables Kubernetes users to create vSphere Namespaces from
templates configured through the automation APIs or vSphere Client. To activate the Namespace
Self-Service on a cluster, use one of the following options:
n Create a self-service namespace template and then activate the Namespace Self-Service on
the cluster.
Currently, only one namespace self-service template is allowed per vSphere Namespace.
After a DevOps engineer creates a namespace from the template, the namespace can
also be deleted through kubectl. You can verify whether a namespace is created
from a template by retrieving the value of the getSelfServiceNamespace() flag of the
com.vmware.vcenter.namespaces.InstancesTypes.Info object that you receive when you call the
get(String namespace) method of the Instances interface.
You define the following configuration settings and resource limitations of the template:
Parameter Description
setResourceSpec(Structure resourceSpec) The resource quotas, such as CPU and memory, that
are reserved for the namespace on the vCenter Server
instance. The CPU limit is set in MHz and the minimum value
is 10 MHz. The memory and the storage limits are set in
MiB. For more options to configure resource limits for the
namespace, see the ResourceQuotaOptionsV1 class in the
API Reference documentation.
Once you have the template created, you can activate the Namespace Self-Service on the
cluster by calling the activate(java.lang.String cluster) method of the NamespaceSelfService
interface. If you want to restrict DevOps users to use the namespace template on a cluster,
you can deactivate the Namespace Self-Service feature. Then users are able to delete only the
namespaces already created from the template.
Starting with vSphere 7.0 Update 2a, DevOps engineers can use the VM Service functionality to
deploy and run VMs on a namespace through the kubectl commands. You can use the vSphere
with Tanzu automation APIs to manage the two VM Service components: VM classes and content
libraries. For more information about managing content libraries in the context of vSphere with
Tanzu, see Content Libraries in vSphere with Tanzu.
You can use the automation APIs to create and manage VM classes. A VM class specification
defines the number of CPUs, memory capacity, and resource reservation settings of the
desired virtual machine. vSphere with Tanzu currently offers twelve ready-to-use VM classes
(T-shirt sizes) that are derived from the most popular VMs in Kubernetes. Based on the
resource reservation that a VM specification requests, each predefined VM class has two
editions: guaranteed and best effort. The guaranteed VM class fully reserves the configured
resources. A best effort VM class does not guarantee any resource reservations and allows their
overcommitment.
You associate a VM class with a specific namespace to make it available to the DevOps engineers
who have access to that namespace. You can assign any number of existing VM classes or create
a custom one. Note that VMs deployed by the DevOps engineers through the VM Service can
only be managed with the kubectl commands. A VM provisioned by DevOps engineers shares
the same resources in a namespace as containers.
A VM class specifies the CPU, memory, and resource reservations for a VM. vSphere with
Tanzu offers several preconfigured VM classes which you can use as is, edit, or delete. You
can also create a custom VM class in your vCenter Server instance and it will be available to all
Supervisors and the namespaces created in these clusters. Note that even though a VM class
is available to all namespaces, a DevOps user can only use the VM classes associated with the
namespaces that he/she can access.
Prerequisites
Required privileges:
Procedure
1 Create the specification of the VM class object by defining the following options.
Option Description
setId(String id) The identifier of the VM class must follow these DNS
requirements:
n A unique name in the current vCenter Server
instance.
n An alphanumeric name with maximum 63 characters.
n No uppercase letters of spaces.
n A dash can be used anywhere except as a first or
last character.
Note that after a VM class is created, you cannot edit its
ID.
What to do next
After you create the custom VM class, you can edit its parameters or delete it from your
environment. See Editing or Removing a VM Class from Your Environment.
You can make your VM class available to DevOps engineers by associating it with a namespace.
See Associating a VM Class with a vSphere Namespace.
Note that editing a VM class specification does not affect the VMs that are already deployed by
the DevOps engineers from this class. Only newly deployed VMs will use the reconfigured VM
class.
Deleting a VM class results in its removal from all related namespaces. All VMs deployed with this
VM class remain unchanged but DevOps engineers can no longer use it.
You can list all VM classes available for a vCenter Server instance by calling the list method
of the VirtualMachineClasses interface. You receive a list of all VM classes and a detailed
information about each one of them. Based on the detailed information, you can narrow the
list and retrieve the IDs of the VM classes that you want to edit or delete.
You can associate one or more VM classes with a single namespace or you can add one VM
class to several namespaces. You can use the predefined VM classes that vSphere with Tanzu
provides or you can create custom ones. See Create a VM Class in vSphere with Tanzu.
Since VM Service is the feature responsible for handling VM classes, you must make that service
aware of the VM classes available to the engineers using a specific namespace. You can achieve
this when you create a new namespace or edit an existing one. See Managing Namespaces on a
Supervisor.
When you create the VM Service specification set the list of VM classes that
must be used to create VMs on the specific namespace. You achieve this by
calling the setVmClasses(java.util.Set<java.lang.String> vmClasses) method of the
VirtualMachineClasses object.
You can also associate one or more content libraries with a namespace that has the VM Service
enabled. See Associating a Content Library with a Namespace.
n Managing Certificates
Managing Certificates
Starting with vSphere 6.7 Update 2, you can use the vSphere Automation API to manage
certificates in your vSphere environment. You can not only refresh default certificates that are
issued by the VMware Certificate Authority (VMCA) but also add third-party or custom-made
certificates to your environment.
n TrustedRootChains
n VMCARoot
n TLSCSR
n TLS
n SigningCertificate
List TrustedRoo list() You can retrieve the identifiers of all trusted root vSphere 6.7 U2
trusted tChains certificates that are present in vCenter Server.
root
certificat
es
Get TrustedRoo get(chain) You can retrieve a root certificate chain by vSphere 6.7 U2
trusted tChains providing its identifier. You can retrieve the
root identifier by using the List trusted root certificates
certificat operation.
e
informati
on
Add a TrustedRoo create(spec) You can add a trusted root certificate chain to vSphere 6.7 U2
trusted tChains your vCenter Server system.
root
certificat
e
Delete a TrustedRoo delete(chain) You can delete a root certificate by providing its vSphere 6.7 U2
trusted tChains unique identifier. You can retrieve the identifier
root by using the List trusted root certificates
certificat operation.
e
Replace VMCARoot create(spec) You can replace the VMCA root certificate with vSphere 7.0
the a new VMCA-signed certificate. The operation
VMCA triggers a restart of the services that are using
root this certificate.
certificat
e
Generate TLSCSR create(spec) You can generate a CSR and use it to issue a vSphere 6.7 U2
a CSR custom certificate from the given spec.
Get the TLS get() You can retrieve the machine SSL certificate of vSphere 6.7 U2
Machine your vCenter Server system.
SSL
certificat
e
Renew TLS renew(duration You can renew the validity of the machine SSL vSphere 6.7 U2
the ) certificate for a specified period in days. The
Machine duration must be less than or equal to 730 days.
SSL If you pass null/None, the default duration of 730
certificat days is applied.
e
Replace TLS set(spec) You can replace the vCenter Server machine SSL vSphere 6.7 U2
the certificate with a custom certificate signed by
Machine an external or a third-party Certificate Authority
SSL (CA).
certificat
e with a
custom
signed
certificat
e
Replace TLS replaceVmcaSig You can replace the vCenter Server machine SSL vSphere 7.0
the ned(spec) certificate with a VMCA-signed certificate.
Machine
SSL
certificat
e with a
VMCA-
signed
certificat
e
Retrieve SigningCer get() You can retrieve the STS signing certificate vSphere 7.0 U3
the STS tificate chains, which are used for validating tokens
signing signed by vCenter Server.
certificat
e chains
Replace SigningCer set(spec) You can replace the current STS signing vSphere 7.0 U3
the STS tificate certificate with a certificate of your choice. The
signing accepted file format is PEM.
certificat
e
Refresh SigningCer refresh(force) You can replace the current STS signing vSphere 7.0 U3
the STS tificate certificate with a new VMCA-signed certificate.
signing The newly-generated certificate is set as the
certificat active STS signing certificate for the vCenter
e Server token service. You can pass true as a
value to the force parameter for environments
that might otherwise prevent the operation from
succeeding.
Adding a root certificate or certificate chain to the vCenter Server trusted certificate store
establishes trust with an enterprise or third-party certificate authority. You can add a root
certificate to vCenter Server as a prerequisite for other scenarios such as setting a third-party
or enterprise machine SSL certificate.
Prerequisites
n Verify that the root certificate or certificate chain you want to add is available on your
machine.
Procedure
1 (Optional) Retrieve the root certificates on your vCenter Server system by calling the list
function of the TrustedRootChains interface.
2 Create a X509CertChain instance with the root certificate you want to add.
4 To add the root certificate, call the create function of the TrustedRootChains interface.
If the operation is successful, the system returns the unique identifier of the trusted root
certificate you added.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
"""
Description: Demonstrates the import of the TRUSTED ROOT CHAIN into vCenter
Sample Prerequisites:
- The user invoking the API should have the CertificateManagement.Manage or the
CertificateManagement.Administer privilege
"""
parser = sample_cli.build_arg_parser()
parser.add_argument('--certchain',
required=True,
help='The certificate chain to be imported into vCenter.')
args = sample_util.process_cli_args(parser.parse_args())
session = requests.session()
session.verify = False if args.skipverification else True
# Login to vCenter
vsphere_client = create_vsphere_client(server=args.server,
username=args.username,
password=args.password,
session=session)
cert_chain = args.certchain.encode(encoding='utf-8').decode('unicode_escape').split(',')
"""
Creation of the spec for input to the API
"""
x509_cert_chain = X509CertChain(cert_chain=cert_chain)
cert_chain = TrustedRootChains.CreateSpec(cert_chain=x509_cert_chain)
print('The alias of the certificate chain successfully imported into vCenter listed below ')
print(vsphere_client.vcenter.certificate_management.vcenter.TrustedRootChains.create(cert_chai
n))
Deleting certificates is not available through the vSphere Client and you can only do this by using
the vSphere Automation API or the CLI tools.
Caution Deleting a root certificate or certificate chain that is in use might cause breakage of
your systems. Proceed to delete a root certificate only if you are sure it is not in use by your
vCenter Server or any connected systems.
Prerequisites
Verify that you have the required privileges for executing the method:
CertificateManagement.Administer and CertificateManagement.Manage.
Procedure
1 (Optional) Retrieve the root certificates from your vCenter Server system by calling the list
function of the TrustedRootChains interface.
The system lists the unique identifiers (chains) of the certificates in the trusted certificate
store.
2 Retrieve the certificate you want to delete by calling the get function and passing the unique
identifier (chain) of the certificate as an argument.
3 Delete the certificate by using the delete function of the TrustedRootChains interface and
passing the unique identifier (chain) of the certificate as an argument.
4 (Optional) To verify you deleted the certificate, list the root certificates from your vCenter
Server system once again.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
"""
Description: Demonstrates the deletion of the TRUSTED ROOT CHAIN corresponding to the
provided alias
Sample Prerequisites:
- The user invoking the API should have the CertificateManagement.Manage or the
CertificateManagement.Administer privilege
"""
parser = sample_cli.build_arg_parser()
parser.add_argument('--certalias',
required=True,
help='The alias for the certificate chain to be deleted from vCenter.')
args = sample_util.process_cli_args(parser.parse_args())
session = requests.session()
session.verify = False if args.skipverification else True
# Login to vCenter
vsphere_client = create_vsphere_client(server=args.server,
username=args.username,
password=args.password,
session=session)
cert_alias = args.certalias
The machine SSL certificate is used for server verification and for secure communication such as
HTTPS or LDAPS. The machine certificates are the human-facing certificates in vSphere. They are
used to create an SSL socket on the server side to which SSL clients can then connect.
Changing the machine SSL certificate with one issued by an official or enterprise certificate
authority is an essential part of the Hybrid Mode of vSphere certificate management. In this
mode, you replace the machine SSL certificate and you leave the VMCA to manage all other
certificates automatically. The VMCA is a just-enough internal certificate authority that comes
integral with your vSphere deployment. It has been purpose-built to serve the certificate needs
of your vSphere environment. For more information on vSphere certificate management, see the
vSphere Authentication guide.
Prerequisites
n Verify that the root certificate of the CA you are going to use is available on your machine.
Procedure
1 (Optional) Retrieve the current machine SSL certificate of your vCenter Server system by
calling the get function of the Tls interface.
Parameter/Method Description
b Create the CSR by calling the create(TlsCsrTypes.Spec) method and passing the CSR
specification.
Note The private key corresponding to the public key generated by the CSR is stored in the
vCenter Server keystore and does not leave your system.
6 Set the new custom certificate to your vCenter Server system by using the Tls service.
Parameter/Method Description
setCert / cert The Machine SSL certificate in PEM format. You must also paste the intermediate
CA certificate, if you have one.
setRootCert / root_cert The third-party root CA certificate in PEM format. You must also paste the
intermediate CA certificate, if you have one.
Note You must not provide the private key as it was generated with the CSR and is
already present on your system.
b Set the new certificate to your vCenter Server system by calling the set(TlsTypes.Spec)
method and passing the TLS specification as an argument.
Results
The services using the certificate restart automatically. Wait for your system to reboot and log in.
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
"""
Description: Demonstrates the generation of the Certificate Signing request
for the MACHINE SSL certificate
Sample Prerequisites:
- The user invoking the API should have the CertificateManagement.Administer or the
CertificateManagement.Manage privilege.
"""
parser = sample_cli.build_arg_parser()
parser.add_argument('--keysize',
help='Key size used to generate the private key.'
'keysize will take 2048 bits if not modified')
parser.add_argument('--commonname',
help='Common name of the certificate subject field.'
'common name will take the Primary Network Identifier(PNID) if not
modified.')
parser.add_argument('--organization',
required=True,
help='Organization field in certificate subject.')
parser.add_argument('--organizationunit',
required=True,
help='Organization unit field in certificate subject')
parser.add_argument('--locality',
required=True,
help='Locality field in the certificate subject')
parser.add_argument('--stateorprovince',
required=True,
help='State field in certificate subject')
parser.add_argument('--country',
required=True,
help='Country field in the certificate subject')
parser.add_argument('--emailaddress',
required=True,
help='Email field in Certificate extensions')
parser.add_argument('--subjectaltname',
help='subjectaltname is list of Dns Names and Ip addresses')
args = sample_util.process_cli_args(parser.parse_args())
session = requests.session()
session.verify = False if args.skipverification else True
# Login to vCenter
vsphere_client = create_vsphere_client(server=args.server,
username=args.username,
password=args.password,
session=session)
common_name = args.commonname
organization = args.organization
organization_unit = args.organizationunit
locality = args.locality
state_or_province = args.stateorprovince
country = args.country
email_address = args.emailaddress
if args.keysize is None:
key_size = args.keysize
else:
key_size = int(args.keysize)
if args.subjectaltname is None:
subject_alt_name = args.subjectaltname
else:
subject_alt_name = args.subjectaltname.split(',')
"""
Create the spec for input to the API
"""
spec = TlsCsr.Spec(key_size=key_size,
common_name=common_name,
organization=organization,
organization_unit=organization_unit,
locality=locality,
state_or_province=state_or_province,
country=country,
email_address=email_address,
subject_alt_name=subject_alt_name)
print('Generating the certificate signing request based on the information provided in the
spec ')
print(vsphere_client.vcenter.certificate_management.vcenter.TlsCsr.create(spec))
Note For related code samples, see the vsphere-automation-sdk-python VMware repository
at GitHub.
"""
Description: Demonstrates the replacement of the MACHINE SSL certificate with a custom
certificate signed by an external third party CA.
Sample Prerequisites:
- The user invoking the API should have the CertificateManagement.Administer privilege.
"""
parser = sample_cli.build_arg_parser()
parser.add_argument('--cert',
required=True,
help='Leaf certificate for replace the MACHINE SSL certificate.')
parser.add_argument('--key',
help='The private key.'
'Not required if the gencsr api was used to generated the
certificate signing request.')
parser.add_argument('--rootcert',
help='The root certificate and the intermediate root certificates '
'required to establish the chain of trust.'
'Not required if the certificates are already present in the
vCenter.')
args = sample_util.process_cli_args(parser.parse_args())
session = requests.session()
session.verify = False if args.skipverification else True
# Login to vCenter
vsphere_client = create_vsphere_client(server=args.server,
username=args.username,
password=args.password,
session=session)
cert = args.cert.encode(encoding='utf-8').decode('unicode_escape')
"""
Create the spec for input to the API
"""
spec = Tls.Spec(cert=cert,
key=key,
root_cert=root_cert)
print('The MACHINE SSL certificate will be replaced with the custom certificate ')
vsphere_client.vcenter.certificate_management.vcenter.Tls.set(spec)
You can refresh the current STS signing certificate of your vCenter Server system with a new
VMCA-issued certificate.
There are two valid reasons for refreshing your STS signing certificate or certificate chain.
n If it is close to expiry. The standard lifespan of the vCenter Server STS signing certificate is
10 years. Your vCenter Server system will notify you in advance of STS certificate expiry. An
alarm is triggered once per week when your STS certificate is 90 days away from expiry, and
then daily when seven days away.
n If you already replaced your signing certificate with a third-party or enterprise one and now
want to revert back to a default VMCA-issued certificate. This procedure replaces the custom
or third-party STS signing certificates you added.
Prerequisites
Procedure
1 (Optional) Retrieve the current vCenter Server signing certificate chain by calling the get
function of the SigningCertificate interface.
get()
2 Refresh the vCenter Server signing certificate by calling the refresh function of the
SigningCertificate interface.
Pass true as a value to the force parameter to force the refresh of the signing certificates
in environments that would otherwise prevent the operation from occurring, such as a mixed-
version environment. If null, the refresh of the vCenter Server signing certificate chain is not
forced.
Results
If successful, the system returns the x509 certificate chain issued in accordance with the vCenter
Server policies.
Caution If you used a forced refresh, you must restart your vCenter Server and all linked
services.
Note For a complete and up-to-date version of the Java sample code, see the vsphere-
automation-sdk-java VMware repository at GitHub.
/**
* Sample code to refresh the STS Signing Certificate for the vCenter Server.
* Use the force option to attempt to force the refresh in environments
* that would otherwise fail such as mixed-version environments. On success,
* the new signing certificates will be printed.
*/
public class RefreshSigningCertificate extends SamplesAbstractBase {
private SigningCertificate certService;
protected boolean force;
@Override
protected void parseArgs(String args[]) {
Option forceOption = Option.builder()
.required(false)
.argName("FORCE")
.longOpt("force")
.desc("Attempt to force refresh")
.build();
List<Option> optionList = Arrays.asList(forceOption);
super.parseArgs(optionList, args);
@Override
protected void setup() throws Exception {
this.certService =
vapiAuthHelper.getStubFactory().createStub(SigningCertificate.class,
sessionStubConfig);
}
@Override
protected void run() throws Exception {
X509CertChain newCert= certService.refresh(this.force);
if(newCert == null ) {
System.out.println("ERROR: refresh signing certificate did not return a
certificate");
} else {
System.out.println("New vCenter signing certificate \n"+newCert.toString());
}
}
@Override
protected void cleanup() throws Exception {
// No cleanup required
}
}
In the usual case, you must not replace the vCenter Server STS signing certificate as it is not an
external-facing certificate. The STS is an internal service that enables communication between
various vSphere services. A fresh installation of vSphere 7.0 and later comes with a signing
certificate that is issued with a default duration of 10 years. Replace the STS signing certificate
with a custom or third-party certificate only if your company security policy requires you to do
so.
Prerequisites
n Verify that the custom generated or third-party certificate chain and private key are available
on your machine.
Procedure
a Set the private key by calling the setPrivateKey(privateKey) method. Pass as value
to the privateKey parameter the corresponding unencrypted PKCS#8 private key in
base64-encoded PEM format.
b Set the custom generated or third-party certificate chain in base64-encoded PEM format
by calling the setSigningCertChain(X509CertChain) method. It must be a valid certificate
chain with the leaf certificate marked for Digital Signature key usage. The leaf certificate
must be first in the sequence and the root must be last.
Results
Caution The change of the STS signing certificate might leave systems in the local vCenter
Server domain in a non-functional state. To prevent system failure, restart your vCenter Server
instance and all linked services.
vSphere Trust Authority is a foundational technology that enhances workload security. vSphere
Trust Authority establishes a greater level of trust in your organization by associating an ESXi
host hardware root of trust to the workload itself. For details about vSphere Trust Authority, see
the vSphere Security documentation.
The procedures in this chapter are based on the Java API. For details, see the vSphere
Automation Java API Reference.
You can retrieve details about vSphere Trust Authority Clusters, update the state of a cluster,
and check the result of the update operation.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Retrieve a list of clusters for a vCenter Server instance that are configured as Trust Authority
Clusters by calling the list(TrustAuthorityClustersTypes.FilterSpec spec) method of the
TrustAuthorityClusters interface.
3 Check the result of the last update operation for the same cluster by calling the
get(java.lang.String cluster) method of the TrustAuthorityClusters interface.
You can retrieve, add, update, remove, and retrieve details about Key Providers.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Retrieve a list of Key Providers to see which Key Providers the cluster is using by calling the
list_Task(java.lang.String cluster) method of the Providers interface.
2 Add a new Key Provider which all hosts in the cluster can use by calling the
create_Task(java.lang.String cluster, ProvidersTypes.CreateSpec spec) method of the
Providers interface.
4 Update an existing Key Provider to modify the connection details and primary key for
it by calling the update_Task(java.lang.String cluster, java.lang.String provider,
ProvidersTypes.UpdateSpec spec) method of the Providers interface.
You can list and update server certificates, retrieve, generate, and update client certificates,
generate a CSR, and set the key server credential.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 List the remote server certificates on the configured key servers to verify the trusted key
servers by calling the list_Task(java.lang.String cluster, java.lang.String provider,
CurrentPeerCertificatesTypes.FilterSpec spec) method of the CurrentPeerCertificates
interface.
If the operation is successful, you receive the client certificate in PEM format.
5 Generate a new self-signed client certificate, used to establish a secure connection to the key
server by calling the create_Task(java.lang.String cluster, java.lang.String provider)
method of the ClientCertificate interface.
If the operation is successful, you can provide the newly generated self-signed client
certificate to the key server to establish trust with the Key Provider.
6 Update the client certificate to specify what Key Provider should use to authenticate with
the key server by calling the update_Task(java.lang.String cluster, java.lang.String
provider, ClientCertificateTypes.UpdateSpec spec) method of the ClientCertificate
interface.
7 Generate a certificate signing request (CSR) for the client certificate by calling the
create_Task(java.lang.String cluster, java.lang.String provider) method of the
ClientCertificate interface.
If the operation is successful, you receive the client CSR in PEM format and the host ID which
issued it. The generated CSR can later be signed by a third party. The signed CSR should be
replicated and set on each host.
8 Set the key server credential for key servers that require a password by calling the
set_Task(java.lang.String cluster, java.lang.String provider, char[] credential)
method of the Credential interface.
You can add, list, remove, and retrieve details about TPM CA certificates and TPM endorsement
keys. You can also set and retrieve TPM 2.0 attestation settings.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Add a new TPM CA certificate to a Trusted Cluster to specify a trusted platform OEM
by calling the create_Task(java.lang.String cluster, CaCertificatesTypes.CreateSpec
spec) method of the CaCertificates interface.
3 Remove a TPM CA certificate from a Trusted Cluster because a platform OEM is no longer
trusted by calling the delete_Task(java.lang.String cluster, java.lang.String name)
method of the CaCertificates interface.
4 Retrieve details about a specific TPM CA certificate on a Trusted Cluster to get more
information about the trusted platform OEM by calling the get_Task(java.lang.String
cluster, java.lang.String name) method of the CaCertificates interface.
5 Add a new TPM endorsement key to a Trusted Cluster to specify a trusted ESXi host
by calling the create_Task(java.lang.String cluster, EndorsementKeysTypes.CreateSpec
spec) method of the EndorsementKeys interface.
6 Retrieve a list of configured TPM endorsement keys in a Trusted Cluster to identify the
trusted ESXi hosts by calling the list_Task(java.lang.String cluster) method of the
EndorsementKeys interface.
7 Remove a TPM endorsement key from a Trusted Cluster because an ESXi host is no longer
trusted by calling the delete_Task(java.lang.String cluster, java.lang.String name)
method of the EndorsementKeys interface.
8 Retrieve details about a specific TPM endorsement key on a Trusted Cluster to get more
information about the trusted ESXi host by calling the get_Task(java.lang.String cluster,
java.lang.String name) method of the EndorsementKeys interface.
9 Set the TPM 2.0 attestation settings by specifying that TPM endorsement keys on a Trusted
Cluster do not need to be signed because the trusted OEM does not sign endorsement keys
by calling the update_Task(java.lang.String cluster, SettingsTypes.UpdateSpec spec)
method of the Settings interface.
10 Determine the TPM 2.0 attestation settings in a Trusted Cluster by calling the
get_Task(java.lang.String cluster) method of the Settings interface.
You can import, list, remove, and retrieve details about ESXi base images.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Import ESXi metadata as a new trusted base image to each host in a vSphere Trust Authority
Cluster by calling the importFromImgdb_Task(java.lang.String cluster, byte[] imgdb)
method of the BaseImages interface.
2 Retrieve a list of trusted ESXi base images in a vSphere Trust Authority Cluster by calling the
list_Task(java.lang.String cluster, BaseImagesTypes.FilterSpec spec) method of the
BaseImages interface.
3 Remove an ESXi base image that should no longer be trusted from a vSphere Trust Authority
Cluster by calling the delete_Task(java.lang.String cluster, java.lang.String version)
method of the BaseImages interface.
4 Retrieve details about a trusted ESXi base image version in a vSphere Trust Authority Cluster
by calling the get_Task(java.lang.String cluster, java.lang.String version) method of
the BaseImages interface.
You can use the retrieved information to connect to the hosts running the vSphere Trust
Authority components.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Retrieve detailed information, including the certificates, about the Attestation Service
instance running on a Trust Authority Host by calling the get(java.lang.String host)
method of the Attestation interface.
2 List Trust Authority Hosts running an Attestation Service instance by using filters by calling
the list(AttestationTypes.FilterSpec spec, AttestationTypes.SummaryType projection)
method of the Attestation interface.
3 Retrieve detailed information, including the certificates, about the Key Provider Service
instance running on a Trust Authority Host by calling the get(java.lang.String host)
method of the Kms interface.
4 List Trust Authority Hosts running a Key Provider Service instance by using filters by calling
the list(KmsTypes.FilterSpec spec, KmsTypes.SummaryType projection) method of the Kms
interface.
You can register, list, remove, and retrieve details about Key Provider Service and Attestation
Service instances.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
The Key Provider Service instance is propagated to all Workload ESXi hosts that the
Workload vCenter Server manages.
The Attestation Service instance is propagated to all Workload ESXi hosts that the Workload
vCenter Server manages.
3 List Key Provider Service instances registered in a Workload vCenter Server by using filters
by calling the list(ServicesTypes.FilterSpec spec) method of the Services interface from
the com.vmware.vcenter.trusted_infrastructure.kms package.
4 List Attestation Service instances registered in a Workload vCenter Server by using filters by
calling the list(ServicesTypes.FilterSpec spec) method of the Services interface from the
com.vmware.vcenter.trusted_infrastructure.attestation package.
The Workload ESXi hosts can no longer retrieve keys by using that Key Provider Service
instance.
The Workload ESXi hosts can no longer attest that their configuration is secure by using that
Attestation Service instance.
7 Retrieve detailed information, including the certificates, for a registered Key Provider Service
instance by calling the get(java.lang.String service) method of the Services interface
from the com.vmware.vcenter.trusted_infrastructure.kms package.
8 Retrieve detailed information, including the certificates, for a registered Attestation Service
instance by calling the get(java.lang.String service) method of the Services interface
from the com.vmware.vcenter.trusted_infrastructure.attestation package.
You can configure, list, remove, and retrieve details about Key Provider Service and Attestation
Service instances.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
You receive the task ID in the response body. You can use the task ID to check the status of
the task by running the following HTTP request.
If the operation is successful, the Key Provider Service instance is propagated to all Trusted
ESXi hosts in the cluster.
You receive the task ID in the response body. You can use the task ID to check the status of
the task by running the following HTTP request.
If the operation is successful, the Attestation Service instance is propagated to all Trusted
ESXi hosts in the cluster.
3 List Key Provider Service instances used by a cluster by using filters by calling the
list(java.lang.String cluster, ServicesTypes.FilterSpec spec) method of the Services
interface from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms
package.
If the operation is successful, the Trusted ESXi hosts can no longer retrieve keys by using that
Key Provider Service instance.
If the operation is successful, the Trusted ESXi hosts can no longer attest that their
configuration is secure by using that Attestation Service instance.
7 Retrieve detailed information, including the certificates, for a configured Key Provider
Service instance used by a Trusted Cluster by calling the get(java.lang.String
cluster, java.lang.String service) method of the Services interface from the
com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms package.
You can establish and remove trust between a Workload vCenter Server and the hosts in a
vSphere Trust Authority Cluster. You can also list all Workload vCenter Server instances that
have established trust with the host in a vSphere Trust Authority Cluster.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Establish trust between a vSphere Trust Authority Cluster and a Workload vCenter Server by
creating a profile, so that the Workload vCenter Server can retrieve the health status of the
vSphere Trust Authority components by calling the create_Task(java.lang.String cluster,
ConsumerPrincipalsTypes.CreateSpec spec) method of the ConsumerPrincipals interface.
2 Remove the trust between a Workload vCenter Server and the hosts in the vSphere Trust
Authority Cluster, so that the Workload vCenter Server stops using the hosts for attestation
by calling the delete_Task(java.lang.String cluster, java.lang.String profile) method
of the ConsumerPrincipals interface.
3 List all profiles which the vSphere Trust Authority Cluster trusts by calling
the list_Task(java.lang.String cluster, ConsumerPrincipalsTypes.FilterSpec spec)
method of the ConsumerPrincipals interface.
You can retrieve basic and detailed information about the health of Key Provider Service or
Attestation Service configurations applied to a Trusted Cluster with respect to the desired state.
You can also retrieve detailed information about the health of all applied vSphere Trust Authority
component configurations in a Trusted Cluster.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Retrieve a summary about the health status of all Key Provider Service instances
configured for use in a Trusted Cluster by calling the list_Task(java.lang.String cluster,
ServicesAppliedConfigTypes.FilterSpec spec) method of the ServicesAppliedConfig
interface from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms
package.
If the operation is successful, you can verify whether all Key Provider Service configurations
of the Trusted Cluster are applied successfully and every host in the cluster is consistent with
the desired state.
2 Retrieve detailed information about the health status of a specific Key Provider Service
instance configured for use in a Trusted Cluster by calling the get_Task(java.lang.String
cluster, NetworkAddress address) method of the ServicesAppliedConfig interface from the
com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms package.
If the operation is successful, you can verify whether the specified Key Provider Service
configuration of the Trusted Cluster is applied successfully and every host in the cluster is
consistent with the desired state.
If the operation is successful, you can verify whether all Attestation Service configurations of
the Trusted Cluster are applied successfully and every host in the cluster is consistent with
the desired state.
4 Retrieve detailed information about the health status of a specific Attestation Service
instance configured for use in a Trusted Cluster by calling the get_Task(java.lang.String
cluster, NetworkAddress address) method of the ServicesAppliedConfig interface from the
com.vmware.vcenter.trusted_infrastructure.trusted_clusters.attestation package.
If the operation is successful, you can verify whether the specified Attestation Service
configuration of the Trusted Cluster is applied successfully and every host in the cluster is
consistent with the desired state.
5 Retrieve detailed information about the health status of all vSphere Trust
Authority components configured for use in a Trusted Cluster by calling the
get_Task(java.lang.String cluster) method of the ServicesAppliedConfig interface from
the com.vmware.vcenter.trusted_infrastructure.trusted_clusters package.
If the operation is successful, you can verify whether the vSphere Trust Authority component
configuration is applied successfully and every host in the cluster is consistent with the
desired state.
What to do next
If there are errors, you can try to remediate the Trusted Cluster. See Remediate a Trusted
Cluster.
You can update the applied Key Provider Service or Attestation Service configurations in a
Trusted Cluster to become consistent with the desired state or you can remove the applied Key
Provider Service or Attestation Service configurations. You can also update all applied vSphere
Trust Authority component configurations in a Trusted Cluster or remove the configurations. By
removing the configurations, you can move hosts from a Trusted Cluster to another cluster.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
1 Remediate all Key Provider Service instances configured for use in a Trusted Cluster by
calling the update_Task(java.lang.String cluster) method of the ServicesAppliedConfig
interface from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms
package.
If the operation is successful, the Key Provider Service configuration of every host in the
cluster is consistent with the desired state.
2 Remove all Key Provider Service configurations from a Trusted Cluster by calling the
delete_Task(java.lang.String cluster) method of the ServicesAppliedConfig interface
from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters.kms package.
If the operation is successful, the applied Key Provider Service configurations are removed
from the configuration of every host in the cluster without affecting the desired state.
If the operation is successful, the Attestation Service configuration of every host in the cluster
is consistent with the desired state.
4 Remove all Attestation Service configurations from a Trusted Cluster by calling the
delete_Task(java.lang.String cluster) method of the ServicesAppliedConfig interface
from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters.attestation
package.
If the operation is successful, the applied Attestation Service configurations are removed
from the configuration of every host in the cluster without affecting the desired state.
5 Remediate all vSphere Trust Authority components configured for use in a Trusted Cluster by
calling the update_Task(java.lang.String cluster) method of the ServicesAppliedConfig
interface from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters package.
If the operation is successful, the vSphere Trust Authority component configuration of every
host in the cluster is consistent with the desired state.
6 Remove all vSphere Trust Authority component configurations from a Trusted Cluster by
calling the delete_Task(java.lang.String cluster) method of the ServicesAppliedConfig
interface from the com.vmware.vcenter.trusted_infrastructure.trusted_clusters package.
If the operation is successful, the applied vSphere Trust Authority component configurations
are removed from the configuration of every host in the cluster without affecting the desired
state.
What to do next
You can recheck the Trusted Cluster health after the remediation. See Check Trusted Cluster
Health.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
2 Retrieve detailed information about a specific TPM device, including the manufacturer, model,
and firmware version by calling the get(java.lang.String host, java.lang.String tpm)
method of the Tpm interface.
You can retrieve the TPM event log for different purposes, such as configuring firmware trust
with an attestation service or validating the boot time TPM measurements. You can unseal a
secret that is bound to an endorsement key to verify reported measurements. For example, you
can verify measurements from the TPM event log.
Prerequisites
n Verify that you have access to a working vSphere Trust Authority environment.
Procedure
2 Retrieve detailed information about a specific TPM endorsement key by calling the
get(java.lang.String host, java.lang.String tpm, java.lang.String key) method of the
EndorsementKeys interface.
3 Retrieve the event log associated with a TPM device by calling the get(java.lang.String
host, java.lang.String tpm) method of the EventLog interface.
administrator A user has read and write access to configuration settings, but cannot manage
user accounts.
super administrator A user has all the capabilities of the other roles, and has the additional
capabilities of creating local user accounts and accessing the local Bash shell.
This model applies to the API and all other interfaces to vCenter Server except when you use
SSH and log in by using a local account.
Authorization Level vCenter Single Sign-On Group vCenter Server Local Role
When a super administrator adds user accounts, the options available include a choice of the role
to assign to the new user.
Operators are allowed to view information about vCenter Server. They are not allowed to alter
its configuration. The operator role is suited for monitoring and reporting functions. For example,
the operator role provides access to the following methods.
n resources.system.health.get
n resources.storage.stats.list
n services.status.get
An administrator role is required for users who alter the vCenter Server configuration, exercise
control functions, or other operations that can affect regular users.
For example, the administrator role provides access the following methods.
n networking.ip4v.renew
n networking.firewall.addr.inbound.add
n services.control
n shutdown.reboot
The superAdmin role allows unrestricted access to vCenter Server. This role is required for
adding or altering user accounts and for using the Bash shell.
Currently, it is very hard to find out the minimal set of privileges that are required to run a specific
workflow of operations. The PrivilegeChecks interface provides methods for retrieving a list of
the latest privilege checks along with the corresponding sessions, users, managed objects, and
operation IDs (opIDs).
Operation Description
List privilege checks Returns a list of privilege checks that match criteria which
you specified.
Get latest privilege check Returns a marker to the last recorded privilege check.
This allows retrieving all privilege checks up to or after a
specified moment in time.
When you retrieve a list of privilege checks, the results are returned in pages due to the possibly
large number of privilege checks that can be returned. You can control the page size either
through a com.vmware.vcenter.authorization.PrivilegeChecks.IterationSpec structure, which
is passed as an argument to the API call, or with the config.vpxd.privCheck.pageSize advanced
setting.
OpIDs OpIDs of the requests for which the check was performed.
If null, all opIDs match.
Sessions Sessions for which the check was performed. If null, all
sessions match.
config.vpxd.privCheck.pageSize Specifies the default page size for privilege checks lists.
Install Stage 2
The vCenter Server API provides methods for performing stage 2 deployment operations on a
newly installed vCenter Server instance.
The vCenter Server instance is deployed in two stages. With stage 1 of the deployment process,
you deploy the OVA file, which is included in the installer. With stage 2 of the deployment
process, you set up and start the services of the newly deployed vCenter Server instance.
To complete stage 1 of the deployment process, you can use the GUI installer or perform a
CLI deployment. For details, see vCenter Server Installation and Setup. Alternatively, you can
perform a deployment by using the VMware OVF Tool. See OVF Tool User's Guide.
After stage 1 of the deployment process completes successfully, the vCenter Server instance
enters in an INITIALIZED state. If the instance is not initialized, you cannot run stage 2 of the
deployment process. You can get the state of the vCenter Server instance by using the vcenter
deployment service. The vCenter Server instance can enter six states during the deployment
process.
NOT_
INITIALIZED Install
Stage 1
Start Success
Check spec
CONFIG_
INITIALIZED IN_ CONFIGURED
PROGRESS
Error
Question
Answer
FAILED
QUESTION_
RAISED
State Description
FAILED Errors occurred during the setup process. You can check
the errors, warnings, and info data structures.
Table 13-4. User Operations lists operations that you can perform to set up your newly deployed
vCenter Server instance.
Operation Description
Get deployment You can retrieve information about the current deployment status. This operation is useful
information both before initiating stage 2 of the deployment and for monitoring the progress of the
setup process.
Validate the You can optionally verify whether your install spec is valid before starting the setup
configuration document process.
Configure the vCenter You can initiate the setup process by providing an install spec that defines the values for
Server instance the settings that you want to configure.
Get question You can retrieve a question raised during the setup process.
Answer question You can provide an answer to the question raised during the setup process. The available
answer values are YES, NO, OK, CANCEL, ABORT, RETRY, and IGNORE. The possible answer
values depend on the type of the question.
Note Each question has a default answer value. If you set questions to receive automatic
answers in the install spec and a question is raised during the setup process, the default
answer value is automatically provided as the answer to the question.
Figure 13-2. Install Workflow and Figure 13-3. Install Stage 2 Workflow show example install
workflows.
During stage 1, the vCenter Server instance is in a NOT_INITIALIZED state. After a successful
deployment, the vCenter Server instance enters in an INITIALIZED state. If there are errors during
stage 1, the vCenter Server instance stays in a NOT_INITIALIZED state and you must redeploy it.
You can check the state of the vCenter Server instance before, during, and after the setup
process. You can run the install stage 2 process if the vCenter Server instance is initialized. You
can check the setup configuration before you initiate stage 2 by running pre-checks. If errors or
warnings appear during the validation of the install specification, you must remove the causes
and correct the specification.
During the setup process, the regular vCenter Server instance state is CONFIG_IN_PROGRESS. The
vCenter Server instance can also enter in a FAILED or QUESTION_RASED state. If a question appears
during the setup, the vCenter Server instance enters in a QUESTION_RAISED state and stays in
it until you provide an answer. You can set questions to receive automatic answers in the
install spec and if a question is raised during the setup process, the default answer value is
automatically provided as the answer to the question.
If errors occur during the setup process, the vCenter Server instance enters in a FAILED state and
you must restart the setup after the causes are removed. If the setup is successful, the vCenter
Server instance enters in a CONFIGURED state.
Start
Yes
No Receive
Successful Answer
Yes
Yes
State= No
CONFIGURED
Yes
End
For information about the states of the vCenter Server instance and available operations, see
Setting Up a Newly Installed vCenter Server Instance.
Start
End
You can run the setup pre-checks and the install stage 2 process by creating and passing an
InstallSpec. In InstallSpec, you define the setup configuration. See Figure 13-3. Install Stage 2
Workflow . You can run the setup in silent mode by setting the InstallSpec.auto_answer to true.
The default value of InstallSpec.auto_answer is false and the setup is in interactive mode, in
which you must provide answers to the raised questions.
For information about the classes, variables, and default values, see the API reference
documentation.
The backup process collects key files into a tar bundle and compresses the bundle to reduce
network load. To minimize storage impact, the transmission is streamed without caching in the
vCenter Server instance. To reduce total time required to complete the backup operation, the
backup process handles the different components in parallel.
You have the option to encrypt the compressed file before transmission to the backup storage
location. When you choose encryption, you must supply a password which can be used to
decrypt the file during restoration.
The backup operation always includes the vCenter Server database and system configuration
files, so that a restore operation has all the data needed to re-create an operational vCenter
Server instance. Current Alarms are included as well. You also have the option to specify
additional data sets, called parts. In this release, you can specify a data set that includes
Statistics, Events, and Tasks.
Choose one of these protocols as the backup location type when you invoke the operation.
n FTP
n FTPS
n SCP
n HTTP
n HTTPS
n NFS
n SMB
The value PATH for the location type field indicates a locally mounted volume.
Note If you specify the SCP protocol, you must specify an absolute path as the value of the
location type field when you create the backup job.
You can do this task when you are choosing a backup storage location or whenever your existing
storage location might be approaching full capacity.
Prerequisites
n Verify that you are familiar with authentication methods. See Chapter 4 Authentication
Mechanisms.
Procedure
3 For each available backup part, request the size of the backup file.
The backup process calculates the compressed size of each backup part.
4 Choose which parts to include in the backup, and sum their sizes.
The backup storage server must have sufficient space to contain the chosen parts.
What to do next
After you choose which backup parts you will store, and verify that the backup storage server
has sufficient free space, you can launch a backup job. For information, see Back up a vCenter
Server Instance by Using the API.
Python Example of Calculating the Size Needed To Store the Backup Image
This example shows how to use Python to collect the information you need to calculate the size
needed to store a backup image of the vCenter Server instance.
This procedure explains the sequence of operations you use to create a backup file of the
vCenter Server instance. You can do this as part of a regular maintenance schedule.
Prerequisites
n Verify that the vCenter Server instance is in a ready state. All processes with start-up type
automatic must be running.
n Verify that the destination storage location is accessible to the backup process.
n Verify that the path to the destination directory exists, as far as the parent directory.
n If the destination directory does not exist, the backup process creates it. If the directory does
exist, verify that it is empty.
n Verify that the destination storage device has sufficient space for the backup file. For
information about how to calculate the space needed for the backup file, see Calculate the
Size Needed To Store the Backup File.
Procedure
The request specifies several attributes, especially the backup location, the protocol used to
communicate with the storage server, the necessary authorization, and which optional parts
of the database you want to back up. The core inventory data and Alarms are always backed
up, but you can choose whether or not to back up Statistics, Events, and Tasks. Collectively,
this optional part of the backup is referred to as seat.
4 From the response, save the unique job identifier of the backup operation.
n my_storage_server
n my_backup_folder
n my_scp_user
n my_scp_password
n my_stub_config
When you back up the vCenter Server instance, you need two sets of authentication credentials.
The API client needs to authenticate to the vCenter Server instance, and the backup service
needs to authenticate to the backup storage server.
The example assumes that your API client has already authenticated the connection to the
vCenter Server instance, and the security context is stored in my_stub_config.
In the backup request, you need to specify the folder that will contain the backup image. The
folder name must be specified as a path name relative to the home directory of the user that
authenticates with the storage server.
You can keep existing backups on the backup server. The retention policy defines the maximum
number of backups that the server keeps. You can also specify whether the backup job should
run once, or on a recurring basis. The recurrence policy defines the days of the week and specific
times at which the backup job is scheduled to run.
Prerequisites
n Verify that you can access the backup server and you have read and write permissions.
Procedure
3 Create a schedule by specifying the backup location, user credentials to access the location,
retention, and recurrence information.
What to do next
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
# Connect to vAPI services
self.stub_config = vapiconnect.connect(
host=args.server,
user=args.username,
pwd=args.password,
skip_verification=args.skipverification)
self.schedule_client = Schedules(self.stub_config)
...
def create_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo(
days=self.days,
hour=self.hour,
minute=self.minute)
create_spec = Schedules.CreateSpec(
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
self.schedule_client.create(self._schedule_id, create_spec)
def update_schedule(self):
retention_info = Schedules.RetentionInfo(self.max_count)
recurrence_info = Schedules.RecurrenceInfo(
days=self.days,
hour=self.hour,
minute=self.minute)
update_spec = Schedules.UpdateSpec(
location=self.location,
location_user=self.location_user,
location_password=self.location_password,
recurrence_info=recurrence_info,
retention_info=retention_info)
self.schedule_client.update(self._schedule_id, update_spec)
def get_schedule(self):
self.schedule_client = Schedules(self.stub_config)
schedule_spec = self.schedule_client.get(self._schedule_id)
recurrence_info = schedule_spec.recurrence_info
retention_info = schedule_spec.retention_info
table = []
data = [self._schedule_id,
"{}:{}".format(recurrence_info.hour, recurrence_info.minute),
" ".join(recurrence_info.days),
retention_info.max_count]
table.append(data)
headers = ["Schedule ID", "Time", "Days", "Retention"]
print(tabulate(table, headers))
...
The process of restoring a vCenter Server instance from a backup has two phases.
1 Deploy a new vCenter Server instance. OVF deployment is described in the vSphere
Automation SDKs Programming Guide.
2 Invoke the restore operation from the Management API to apply configuration settings and
load the vCenter Server database from the backup file.
Note You cannot specify optional parts for the restore operation. The restore operation includes
all optional parts, such as Events and Tasks, that were specified at the time when the backup file
was created.
When you restore your vCenter Server instance from a backup file, it begins in an unconfigured
state. During this time, you must use basic authentication to access the Management API. When
you use basic authentication, do not use the vSphere Automation API endpoint. Instead, you
must connect your client to port 5480 of the vCenter Server instance.
When you use basic authentication, you must pass user name and password credentials with
each method invocation. Use credentials that are known to the guest operating system of the
vCenter Server instance.
You can write your client to trap the error, but you have no way to know when the vCenter
Server services are running again. To determine when the restore process is complete, you must
retry the API connection until it succeeds, then request the status of the job.
Prerequisites
n A new vCenter Server instance must be deployed in an unconfigured state, except that it
must have a fully qualified domain name or IP address that matches the old one.
n Verify that the new vCenter Server instance has the same build number as the one in the
backup file.
n Verify that the new vCenter Server instance has a size equal to or greater than the old one. If
the old vCenter Server instance was customized to exceed the largest template size, the new
one must be customized to the same size.
n Verify that the destination storage location is accessible to the vCenter Server restore
process.
Procedure
What to do next
After the vCenter Server instance is fully configured by the restore operation, you can resume
using the vSphere Automation API endpoint for subsequent operations.
Python Example of Restoring a vCenter Server Instance
This example shows how to use Python to restore a vCenter Server instance. This operation is
the second phase of restoring the vCenter Server instance from a backup image.
n my_vcsa_hostname
n my_vcsa_username
n my_vcsa_password
n my_backup_name
n my_storage_server
n my_scp_user
n my_scp_password
n my_backup_folder
When you restore the vCenter Server instance from a backup image, you need two sets of
authentication credentials. The API client needs to authenticate to the vCenter Server instance,
and the vCenter Server backup service needs to authenticate to the backup storage server.
The example uses local user name and password authentication for the connection to the
vCenter Server instance because the vSphere Automation API endpoint is not yet running when
you restore the vCenter Server instance. The client must connect to port 5480 for this operation.
In the restore request, you need to specify the folder that contains the backup image. The folder
name is the same name that was specified in the backup request. It must be specified as a path
name relative to the home directory of the user that authenticates with the storage server.
import requests
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.user_password import create_user_password_security_context
Reconciliation is a post-restore process that checks whether the vCenter Server partners in
embedded linked mode are available, synchronizes the vCenter Server data and services with
the partners, and runs the vCenter Server services. The processes of restore and reconciliation
depend on the topology and if there are changes in the topology between the backup and
restore, you cannot restore the embedded linked mode. If the replication partners are not
available and you try to restore the first node, you must ignore the warnings. In this case, any
changes that are made in the topology or infrastructure after the backup will be lost. If you
restore a node different from the first one, you must add it to the domain of the first node. If
you use a daisy-chain topology, you must first restore the first node, and after that to restore the
second, link it to the first one, and apply the same to the following nodes.
You can use the reconciliation API after a file-based and an image-based restore. After an
image-based restore, you can run the reconciliation process by using the API or UI. After
a file-based restore, you can monitor the reconciliation process by using the GET https://
<vcenter_ip_address_or_fqdn>/api/appliance/recovery/reconciliation/job HTTP request.
For information about how to restore a vCenter Server instance from an image or a file by using
the UI, see the vCenter Server Installation and Setup documentation.
Prerequisites
n Verify that you restored your nodes in the correct order, if you use a daisy-chain topology.
n Verify that you have administrator's credentials to your Single Sign-On domain.
Procedure
1 Create a Job.CreateSpec object, specify user name and password of Single Sign-On
administrator, and set the ignore_warnings field to true.
The default value of ignore_warnings is false. If you do not set ignore_warnings to true, the
reconciliation fails due to the validation warnings.
You can check the result of the operation by reading the Job.Info object. Job.Info contains
information about the job such as description, status, progress, error, start and end time.
You can configure the syslog forwarding by using the API or user interface. For information
about how to manage the syslog by using the user interface, see the vSphere Monitoring and
Performance documentation.
The table below lists operations that you can perform to manage the forwarding of syslog
messages to remote logging servers.
Operation Description
Get forwarding You retrieve information about the log forwarding configuration. For more information
configuration refer to the diagrams below.
Test forwarding You can validate the current log forwarding configuration. Optionally, you can send a test
configuration diagnostic log message from the vCenter Server instance to all configured logging servers
to allow manual end-to-end validation. For more information refer to the diagrams below.
Set forwarding You can change the log forwarding configuration. For more information refer to the
configuration diagrams below.
The forwarding configuration includes the IP or FQDN of the remote server, the remote port
for receiving syslog information, and the communication protocol. The remote server must be
a server with running rsyslog, for example, another vCenter Server instance. The API supports
the TCP, UDP, TLS, and RELP protocols. For information about the supported TLS versions,
see KB article 2147469. By creating a Forwarding.Config object, you specify the connection
with a remote server. For information about the Forwarding class and its methods, see the API
Reference documentation and diagrams below.
You can use several remote servers by creating a list with Forwarding.Config objects
and passing it to the set method. The maximum number of remote servers is three.
You can validate the forwarding configuration by using the test method. The returned
Forwarding.ConnectionStatus object shows the status of the connection between the vCenter
Server instance and a remote server. The State enumeration shows whether the vCenter Server
instance can reach the remote server. State can be UP, DOWN, or UNKNOWN. If the state is DOWN or
UNKNOWN, the vCenter Server instance cannot access the remote server and you must check the
remote server and its settings such as network ports, firewall, supported protocols, and syslog
configuration.
com.vmware.appliance.logging_client
Forwarding(config)
+Config:Forwarding.Config
+ConnectionStatus:ConnectionStatus
+get(): list
+set(cfg_list)
+test(send_test_message): list
Forwarding.Config Forwarding.ConnectionStatus
+hostname:str +hostname:str
+port:long +state:State
+protocol:Protocol +message:LocalizableMessage or None
+TCP +DOWN
+TLS +UP
+UDP +UNKNOWN
+RELP
Start
End
For a code example of configuring the syslog forwarding, see Python Example of Configuring
Syslog Forwarding.
Python Example of Configuring Syslog Forwarding
This example shows how you can configure and test the forwarding of a vCenter Server syslog
by using the API. The example is based on the log_forwarding.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.
...
self.log_forwarding_client = Forwarding(self.stub_config)
...
def set_log_forwarding(self):
log_forwarding_config = [Forwarding.Config(hostname=self.loghost,
port=self.port,
protocol=self.protocol)]
self.log_forwarding_client.set(log_forwarding_config)
def get_log_forwarding(self):
configs = self.log_forwarding_client.get()
def test_log_forwarding(self):
test_response = self.log_forwarding_client.test(True)
def update_log_forwarding(self):
# Read log forwarding configuration
log_forwarding_config = self.log_forwarding_client.get()
...
The following table lists the operations that you can perform to manage support bundles.
Operation Description
Get support bundle You can retrieve a list of components and manifests included in the support bundle.
components Manifests specify the files that must be collected for a component as part of the support
bundle.
List support bundles You can retrieve a list of generated support bundles. The list contains details about each
support bundle.
Create a support bundle You can generate a support bundle. Optionally, you can specify the support bundle
components and the partition where you want to save the support bundle.
You can run support bundle management operations by using the vSphere Automation
SDK or sending an HTTP request. You can use the Components interface to
get support bundle components and the SupportBundleFactory class from the
com.vmware.appliance.support_bundle package to list and create support bundles. For more
information, see the Java API Reference documentation.
Upgrade Stage 2
You can upgrade your vCenter Server instance by using the API, CLI, or GUI.
For information about how to upgrade the vCenter Server instance by using CLI and GUI, see the
vCenter Server Upgrade documentation.
By using the API, you can upgrade your vCenter Server instance. For information about
the upgrade process, its stages, supported configurations, upgrade paths, prerequisites for
upgrading, and the sequence for upgrading a vSphere environment, see the vCenter Server
Upgrade documentation.
After you deploy the vCenter Server instance on stage 1 by using the GUI or CLI, the instance
enters in an INITIALIZED state. If the vCenter Server instance is not initialized, you cannot run
stage 2 of the upgrade process. You can get the state of the vCenter Server instance by using
the vcenter deployment service. There are six states during the upgrade process.
NOT_
INITIALIZED Upgrade
Stage 1
Start Success
Check spec
CONFIG_
INITIALIZED IN_ CONFIGURED
PROGRESS
Error
Question
Answer
FAILED
QUESTION_
RAISED
State Description
You can roll back a vCenter Server instance upgrade by using the GUI. For information about
how to roll back a vCenter Server instance, see the vCenter Server Upgrade documentation.
After the upgrade, you can check the vCenter Server instance type, domain registration,
services, their state and health status by using the API. For information about how to verify
whether the upgrade of your vCenter Server instance is successful, see the vCenter Server
Upgrade documentation.
Table 13-8. User Operations shows operations that you can perform to upgrade your vCenter
Server instance.
Operation Description
Get the state of the vCenter Server instance You can get the state of the vCenter Serverinstance
before, during and after the upgrade process.
Check You can validate the upgrade spec before you run the
upgrade process. If the vCenter Server instance is in
the INITIALIZED state, you can run the validation. The
operation runs upgrade pre-checks. You can check the
errors, warnings, and status data structures before you
run the upgrade process.
Get You can get the raised question. If you set the
Upgrade.auto_answer to true, the upgrade process will be
in a silent mode and the vCenter Serverinstance does
not generate questions. It uses default answers and you
should not provide an answer.
For information about the available operations in the API, see the vcenter deployment, vcenter
deployment upgrade, vcenter services, and vcenter system-config deployment type services
in the API reference documentation.
Figure 13-7. Upgrade Workflow and Figure 13-8. Upgrade Stage 2 Workflow show example
upgrade workflows.
During stage 1, the vCenter Server instance is in a NOT_INITIALIZED state. After a successful
deployment, the vCenter Server instance enters in an INITIALIZED state. If there are errors during
stage 1, the vCenter Server instance stays in a NOT_INITIALIZED state and you must redeploy it.
You can check the state of the vCenter Server instance before, during, and after the upgrade
process. You can run the upgrade stage 2 process if the vCenter Server instance is initialized.
You can check the upgrade configuration before you run the upgrade by running pre-checks. If
errors or warnings appear during the validation of the upgrade specification, you must remove
the causes and correct the specification.
During the upgrade process, the vCenter Server instance can enter in a FAILED or
QUESTION_RASED state. If a question appears during the upgrade, the vCenter Server instance
enters in a QUESTION_RAISED state and stays in it until you provide an answer. You can run the
upgrade in silent mode, in which the vCenter Server instance does not generate questions, and
uses default answers.
If errors appear during the upgrade, the vCenter Server instance enters in a FAILED state and
you must remove the causes, redeploy the instance and restart the upgrade. If stage 2 of the
upgrade process is successful, the vCenter Server instance enters in a CONFIGURED state. If the
vCenter Server instance is configured, you can check its services and pause the historical data
transfer.
Start
Yes
Yes No
Run validation of the upgrade spec by using
the vcenter deployment upgrade service
No
Successful
Yes
1 State= No
FAILED
State= No
CONFIGURED No State= Yes
QUESTION_
RAISED
Yes
Yes 1
Receive
Answer
No
Answer
Received?
Yes
End
For information about the states of the vCenter Server instance and available operations, see
Upgrading a vCenter Server Instance.
Start
End
You can run the upgrade pre-checks and the upgrade stage 2 process by creating and passing
an UpgradeSpec. In UpgradeSpec, you define the upgrade configuration and specify the source
vCenter Server instance and the source ESXi host in SourceApplianceSpec and LocationSpec. See
Figure 13-8. Upgrade Stage 2 Workflow . You can run the upgrading in silent mode by setting the
UpgradeSpec.auto_answer to true. The default value of UpgradeSpec.auto_answer is false and
the upgrading is in interactive mode, in which you must provide answers to the raised questions.
For information about the classes, variables, and default values, see the API reference
documentation.
Deferred Import
The deferred import is a process of historical data transfer after the successful migration of a
vCenter Server instance with an external database. The historical data includes statistics, events,
and tasks.
By using the deferred import feature, you can postpone the historical data transfer after the
migration process completes, so that you manage the downtime of your environment. You
can select whether all historical data, or only events and tasks, will be migrated with the core
data during the migration. The historical data transfer and deferred import of historical data are
deactivated by default. You can enable and configure the historical data transfer by using the
API, vCenter Server Management Interface, vCenter Server installer, or CLI installer. A vCenter
Server super administrator can run and control the migration and deferred import processes.
If you use the deferred import feature, the historical data is migrated with the core data and
the historical data import process starts automatically after a successful migration and when the
vCenter Server instance is running. You can pause the historical data import and resume it later.
For information about how to configure and run the migration and deferred import processes
by using the vCenter Server Management Interface, see the vCenter Server Upgrade
documentation.
By using the API, you can configure, control, and monitor the data transfer process. If you use
the API to enable the deferred import feature, you must create a history migration spec and set
defer_import to true. For information about how to configure the deferred import by using the
API, see the API reference.
The data import process has five states that you can check. If the historical data migration
and the deferred import are configured, the historical data import starts automatically after a
successful migration.
PENDING
Pause/error
Start
BLOCKED
RUNNING
Resume
Success
Cancel Cancel
FAILED
SUCCЕEDED
Operation Description
Pause You can pause the running data transfer process. If the data transfer is paused, you can
resume or cancel it.
Cancel You can cancel the data transfer process if it is in a RUNNING or BLOCKED state.
Note If you cancel the data transfer, the process enters in a final FAILED state and you
cannot resume the transfer.
Operation Description
Get status You can retrieve the status of the data transfer process. There are five states.
PENDING
RUNNING
BLOCKED
The transfer is paused or there was a recoverable error, such as not enough disk
space, during the import.
SUCCEEDED
FAILED
You can run the deferred import operations by using the API or sending an HTTP request.
Note When you send the requests, you must use an authentication.
If you pause the data transfer by using the API or an HTTP request, you can resume or cancel the
process by using the API or the vCenter Server Management Interface.
Important If you cancel the transfer process, and want to transfer the historical data later, you
must restart the migration process.
You can check the errors, warnings, and info messages by reading the info, status, and
notifications data structures.
If the information in the data structures is not enough, you can download the vCenter Server
support bundle from <vcenter_ip_address_or_fqdn>:443/appliance/support-bundle and
check the log files.
The historical data transfer during the vCenter Server migration is deactivated by default and
only the core data is migrated. You can enable the historical data transfer and the deferred
import by creating a history migration spec and setting defer_import to true. For example, see
Figure 13-10. Python Class Diagrams for Deferred Import . You can change the historical data
scope by using the HistoryMigrationOption enumeration. By default, the data_set is set to
EVENTS_TASKS.
You can control the deferred import by creating an import history spec and calling the methods
of the ImportHistory class. Figure 13-10. Python Class Diagrams for Deferred Import shows the
classes that you can use to configure and control the deferred import.
HistoryMigrationSpec <<Enumeration>>
HistoryMigrationOption
data_set:HistoryMigrationOption
defer_import:bool or None ALL
EVENTS_TASKS
ImportHistory ImportHistory.CreateSpec
Prerequisites
n Verify that you cloned or downloaded the vSphere Automation SDK for Python from https://
github.com/vmware/vsphere-automation-sdk-python.
n Verify that you set up a test environment. For information about the prerequisites and how to
set up a test environment, see the README.md file in the deferhistoryimport directory and
the Quick Start guide for vSphere Automation SDK for Python at https://github.com/vmware/
vsphere-automation-sdk-python.
n Verify that you opened the vCenter Server Management Interface of your target vCenter
Server instance.
Procedure
You can import only events and tasks or import all historical data.
3 Select Import historical data in the background and complete all steps from the wizard.
Use the IP address of your source vCenter Server instance and the vCenter Server
administrator credentials when you run the sample. You can use or skip the verification of
the vCenter Server certificate. For example, you can use the following command.
Note For a complete and up-to-date version of the sample code, see the vsphere-
automation-sdk-python VMware repository at GitHub.
...
self.service_manager = ServiceManager(args.server,
args.username,
args.password,
args.skipverification)
self.service_manager.connect()
...
# Using REST API service
import_history = ImportHistory(self.service_manager.stub_config)
...
# Change the status - either pause or resume it
start_status = get_defer_history_import_status(import_history)
if start_status == Status.RUNNING:
print('Pausing Defer History Data Import.')
import_history.pause()
...
elif start_status == Status.PAUSED:
print('Resuming Defer History Data Import.')
import_history.resume()
...
The health status indicators report graded values from green to red. The general meanings of the
grades are as follows.
green
yellow
orange
red
gray
The value of the overall system health indicator reflects the strongest trouble indication among
the vCenter Server components. If any component has a red indicator, the overall system health
indicator is red, else if any component has an orange indicator, the overall system health indicator
is orange, and so on.
A gray value for any component indicates that data for the subsystem is unknown. If one or
more components have a gray value, but all other subsystems are green, then the overall system
health indicator is gray rather than green. However, if any component has a definite trouble
indication, the overall system health indicator reflects the strongest trouble indication among the
components.
Prerequisites
Verify that you have an active authenticated session with vCenter Server. This procedure
assumes that the session ID is present in the security context of a stub configuration.
Procedure
1 Create an interface stub or REST path that uses the stub configuration.
n my_stub_config
You can use the statistics to spot peak usage demands or to monitor trends for advance warning
of potential resource exhaustion.
After the monitoring service starts up, it begins requesting statistics from the guest operating
system periodically, at a frequency that depends on the type of statistic. The service requests
storage statistics once every 10 minutes, while it requests memory, CPU, and networking
statistics once per minute. The collection times are fixed relative to the startup time of the
monitoring service, rather than to clock time.
The monitoring service retains statistics approximately 13 months, by default. Older statistics are
deleted by the service, creating a 13-month moving window within which you can query statistics.
You can choose to delete statistics as needed to conserve storage resources.
The guest operating system computes statistics either as rates, such as CPU cycles per second,
or as snapshots of size, such as KB used for storage. Statistics stored as size snapshots are
collected at the end of their sample periods. Statistics stored as rates are computed as averages
of values sampled frequently during each sample period.
When you query the statistics database, the units are not returned with the data, but you can
determine the units for any metric by requesting metadata for the metric with the get() method.
To request data or metadata for a metric, you must supply the ID of the metric. You can get a list
of metric IDs by using the list() method, which returns information on all available metrics.
When you query statistics, you provide a list of IDs to specify the metrics in which you are
interested. You also supply a start time, an end time, a roll-up interval, and a roll-up function.
These values interact as follows to determine the data returned to you.
n The response contains a list of data points for each metric ID you specified in the request.
n The start time and end time control the limits for the data you want in the response. The
response contains data points only for statistics that have timestamps between those limits,
inclusive of the endpoints. However, the start time is adjusted to a round number, in some
cases. For more information, see Statistics Interval Adjustment in vCenter Server.
n The roll-up interval enables you to control the granularity of the data points in the response.
Rather than a response with a data point for every statistic between the start time and end
time, you get a response with a number of data points equal to the number of intervals
between the start and end times. Generally, you should specify a time period that is an even
multiple of the interval, so that each data point in the response represents the same number
of statistics.
n The roll-up function specifies how the response summarizes the statistics that fall within each
interval. The resulting data point can be the maximum statistic value within collection interval,
or the mean of the statistics values within the interval, and so on.
The API does not enable you to determine the exact time that a statistic was collected.
Furthermore, some statistics, such as those for storage metrics, might take seconds or minutes
to collect, so that they are not available immediately at the time a request is made to the guest
operating system.
However, because statistics are collected at regular intervals, and roll-up intervals for a request
generally all have the same size, each data point in the response represents the same number of
statistics as the others. See Statistics Interval Adjustment in vCenter Server for more information.
The monitoring service adjusts the start time of a data collection request when it is not an exact
multiple of the interval length. In these instances, the start time is rounded downward to the
previous UTC time that is a multiple of the interval. All subsequent intervals of the data collection
are also adjusted to align with the new start time.
For example, if the start time is 10:31 and the interval length is 1 hour, the monitoring service
adjusts the start time to 10:00 and the roll-up intervals have the following continuous pattern.
n 10:00 to 10:59:59.999
n 11:00 to 11:59:59.999
n 12:00 to 12:59:59.999
The monitoring service does not adjust the end time of a data collection. Consequently,
the response to a statistics query might contain one more data value than expected, or an
incomplete final interval might be lengthened.
n Empty data values can happen when the report time period is too short to be certain of
containing any statistics. For instance, a time period of 30 seconds is half the length of the
sample period for network metrics, so you have only a 50% chance of finding a network
statistic during any 30-second reporting period.
n Empty data values can also happen when the interval is shorter than the sample period for a
metric you have requested. In this case, some data points are present in the list, while others
are empty because no statistic was collected during those intervals. For instance, an interval
of 5 minutes is only half the length of the sample period for storage metrics, so every second
data value is empty.
n Empty data values can also happen when the monitoring service has not finished collecting
and writing the last sample to the database, even if the nominal sample timestamp falls within
the report time period. For example, calculation of storage used can delay writing a storage
statistic to the database. A request for the statistic during that delay time produces an empty
data point in the response.
When a response contains an empty data value, this indicates that no statistics were collected
during a collection interval. An appropriate action for the client in such a case depends on how
the client is using the data. For example, if you are graphing a resource usage trend, you might
choose to interpolate for the missing value to produce a smooth line.
Prerequisites
This task assumes you have previously authenticated and created a client session.
Procedure
Include metric IDs both for vcdb_core_inventory and vcdb_seat. The name vcdb_seat refers
to Statistics, Events, and Tasks in the vCenter Server database.
Results
The result of this procedure shows the storage used in the vCenter Server database, which
includes storage overhead used for indexes and other optimizations beyond the actual size of
the data.
This example requests statistics at 30-minute intervals for a recent 2-hour report period. The
example requests the storage used by the inventory component and the storage used by the
combination of statistics, events, alarms, and tasks. The example adds the two values to calculate
the vCenter Server database usage in each 30-minute roll-up interval, and then reports the
maximum size found over the 2-hour report period.
# Issue request for core inventory and 'SEAT' (stats, events, & alarms) usage.
req = appliance_client.Monitoring.MonitoredItemDataRequest()
req.names = ['storage.used.filesystem.vcdb_core_inventory',
'storage.used.filesystem.vcdb_seat']
req.interval = appliance_client.Monitoring.IntervalType.MINUTES30
req.function = appliance_client.Monitoring.FunctionType.MAX
d_now = datetime.datetime.utcnow()
req.start_time = d_now - datetime.timedelta( minutes=135 )
req.end_time = d_now - datetime.timedelta( minutes=15 )
Monitoring_stub = appliance_client.Monitoring( my_stub_config )
resp = Monitoring_stub.query( req )
# Add the usage stats for each interval, and display maximum usage.
highest = max( map( (lambda a,b: int(a) + int(b)),
core_sizes, seat_sizes ) )
print( 'vCenter database inventory + stats, events, alarms, tasks:' +
' (max) size = {0} KB'.format( highest ) )
For example, you can query statistics about inventory storage, transaction log, and vCenter
Server tasks. Many of these statistics are available both for storage consumed and storage
available.
This task provides data for system administrators who need to monitor storage consumption in
the guest operating system of vCenter Server.
Prerequisites
Procedure
Include metric IDs for each data type you want to monitor.
req.names = []
for item in mon.keys() :
req.names.append( item )
# Issue request.
Monitoring_stub = appliance_client.Monitoring( my_stub_config )
resp = Monitoring_stub.query( req )
FIPS 140-2 is a U.S. and Canadian government standard that specifies security requirements
for cryptographic modules. vSphere uses FIPS-validated cryptographic modules to match those
specified by the FIPS 140-2 standard. The goal of vSphere FIPS support is to ease the compliance
and security activities in various regulated environments.
The following table lists the operations that you can perform to manage the FIPS settings of your
vCenter Server system.
Operation Description
Get FIPS status You can check whether the global FIPS compliance is currently enabled on the vCenter
Server system.
Manage FIPS status You can enable or deactivate the global FIPS compliance on the vCenter Server system.
Note When you enable FIPS compliance, some components might present functional
constraints. For more information, see vSphere Security.
You can run FIPS management operations by using the vSphere Automation SDK
or sending an HTTP request. You can use the GlobalFips interface from the
com.vmware.appliance.system.security package to check the FIPS status and enable or
deactivate the global FIPS compliance. For more information, see the Java API Reference
documentation.
You can export multiple configuration profiles at once. The exported data can contain general
configuration settings and user content. You can replicate the same configuration across all
vCenter Server instances in your environment by importing the same data package. You can also
use the exported data as a backup if you need to revert to the last known good configuration. To
avoid configuration issues, you can validate the exported data before importing it to a vCenter
Server instance.
The following table lists the operations that you can perform to manage the configuration profiles
in your infrastructure.
Operation Description
List configuration profiles You can retrieve a list of all configuration profiles that are registered with vCenter Server.
Export configuration You can export specific vCenter Server configuration profiles.
profiles
Validate configuration You can validate the exported vCenter Server configuration profiles. The validation
profiles process examines the configuration file for possible errors and conflicts and returns
output. This operation can help avoid configuration issues or loading the wrong
configuration file.
Import configuration You can import specific vCenter Server configuration profiles into another vCenter Server
profiles instance.
You can run infrastructure profile management operations by using the vSphere Automation
SDK or sending an HTTP request. You can use the Configs interface from the
com.vmware.appliance.infraprofile package to list, export, validate, and import configuration
profiles. For more information, see the Java API Reference documentation.
You can use the operations to discover VMware products that can be associated with vCenter
Server, list associated products, and manage product associations. You can also get details
about available vCenter Server updates, perform pre-checks, and produce reports. The reports
can contain interoperability or pre-check information. Interoperability reports contain information
about the interoperability between the associated products and a specific vCenter Server
version. Pre-check reports contain information about the compatibility of the current vCenter
Server version with a pending update version. You can plan to perform vCenter Server updates
based on the information gathered in the produced reports.
The life cycle management API provides operations that are grouped in the discovery, update,
and reports categories. The discovery functionality of the API consists of the operations in the
discovery category. The planning functionality of the API consists of the operations in the update
category. Both functionalities can produce reports that you can download by using the reports
category.
The discovery category provides operations for listing VMware products that can be associated
with vCenter Server, managing products associations, and creating interoperability reports. The
update category provides operations for listing all available updates and upgrades for vCenter
Server and generating a pre-check compatibility report. The reports category provides an
operation for downloading reports generated by interoperability and pre-check operations. By
using the retrieved information, you can select one of the available patches and can plan an
actual patch or upgrade for a specific vCenter Server version.
The following table lists the operations that are available in the discovery category.
Operation Description
Get product catalog You can retrieve a list of all VMware products that can be associated with vCenter Server.
List associated products You can retrieve a list of all VMware product deployments in the environment that are
associated with vCenter Server.
Note The list contains both product deployments discovered automatically and
deployments registered manually through the API.
Get associated product You can retrieve detailed information about a product associated with vCenter Server.
information
Create product You can manually associate a VMware product with vCenter Server.
association
Update product You can modify a manually added VMware product that is associated with vCenter Server.
association
Note You cannot modify VMware products that are discovered automatically.
Delete product You can delete or dissociate a manually added VMware product that is associated with
association vCenter Server.
Note You cannot delete or dissociate VMware products that are discovered
automatically.
Create interoperability You can create an interoperability report between a vCenter Server release version and all
report products registered with the vCenter Server instance.
The following table lists the operations that are available in the update category.
Operation Description
List updates You can retrieve a list of all available vCenter Server updates. The list can contain minor,
in-place, updates and major, migration-based, upgrades.
Get update info You can retrieve detailed vCenter Server information about a specific update or upgrade.
Create pre-check report You can create a vCenter Server pre-update compatibility check report for a pending
update version.
Note You can export and download the report in CSV format.
The following table lists the operations that are available in the reports category.
Operation Description
Get report You can download the report generated by the interoperability and pre-check operations.
For information about downloading the report, see the API reference documentation.
You can run life cycle management operations by using the vSphere Automation SDK or
sending an HTTP request. You can use interfaces from the com.vmware.vcenter.lcm.discovery,
com.vmware.vcenter.lcm.update, and com.vmware.vcenter.lcm packages to perform discovery,
update, and reports operations. For more information, see the Java API Reference
documentation.
This procedure includes the operations that you can use to manage the product catalog and
associated products.
Prerequisites
n Verify that you have an active authenticated session with vCenter Server.
Procedure
6 Delete a product form the list of VMware products associated with vCenter Server.
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 stub configuration
stub_config = StubConfigurationFactory.new_std_configuration(connector)
self.product_client = ProductCatalog(stub_config)
self.associated_products_client = AssociatedProducts(stub_config)
def run(self):
# Product catalog
product_catalog = self.product_client.list()
print("Product catalog list: \n", product_catalog)
# Associated products
associated_products = self.associated_products_client.list()
print("Associated products list : \n", associated_products)
# Add product
spec = {'product_name': 'VMware Identity Manager', 'version': '3.3', 'deployments':
'3'}
add_associated_product = self.associated_products_client.create(spec)
print('Added new product. \n', add_associated_product)
associated_products = self.associated_products_client.list()
print("Associated products after adding the product: \n", associated_products)
# Update product
update_spec = {'deployments': '9'}
update_associated_product =
self.associated_products_client.update(add_associated_product, update_spec)
associated_products = self.associated_products_client.list()
print("Associated products after updating the product: \n", associated_products)
# Delete product
delete_associated_product =
self.associated_products_client.delete(add_associated_product)
associated_products = self.associated_products_client.list()
print("Associated products after deleting the product: \n{0}", associated_products)
...
Prerequisites
n Verify that you have an active authenticated session with vCenter Server.
Procedure
If there are available updates, you can retrieve details about the updates.
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 stub configuration
stub_config = StubConfigurationFactory.new_std_configuration(connector)
self.pending_client = Pending(stub_config)
self.precheck_client = PrecheckReport(stub_config)
def run(self):
# List updates
available_updates = self.pending_client.list()
print("vCenter Server available updates - ", available_updates)
if available_updates.updates:
target_version = available_updates.updates[0].version
update_details = self.pending_client.get(target_version)
print("vCenter Server available update details - ", update_details)
Retrieve a Report
You can retrieve a report generated by the interoperability and pre-check operations by using
the API.
Prerequisites
n Verify that you have an active authenticated session with vCenter Server.
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 stub configuration
stub_config = StubConfigurationFactory.new_std_configuration(connector)
self.report_client = Reports(stub_config)
def run(self):
# Retrieve report
report_details = self.report_client.retrieve('com.vmware.vcenter.lcm.report')
print("Report details - ", report_details)
...
Before applying updates, you must make sure that your environment is prepared for the vCenter
Server software update process.
Security patches usually address vulnerabilities in third-party components and do not affect the
vCenter Server functionality. vCenter Server bug fixes can introduce changes to the functionality
without affecting the data format or database schema of the system.
Each update contains metadata with information about the updated content, for example,
whether high-priority OS updates are included. The update metadata includes a list of
components to be updated, the release date of the update, a list of fixed issues, time and
disk space requirements, and information whether a reboot is required. The metadata can also
contain a new vCenter Server version number, including a build number. In addition to the
metadata, an update can contain optional components such as update scripts, new versions of
vCenter Server software components, and new versions of OS components.
vCenter Server can obtain software updates from either a URL or an ISO image. The URL can
either point to the VMware Web repository or to a custom repository in which you upload the
updates in ZIP format. To perform an update by using an ISO image, attach the image to the
CD/DVD drive of the vCenter Server instance.
There are multiple phases of the update process. For details, see vCenter Server Software
Update Workflow.
If you want to prevent issues related to the possibility of update installation failures, you should
create a backup or take a snapshot of your vCenter Server instance before you start the update
process. A backup can also be useful when an update is successfully installed. For example, you
might decide to revert to the previous version if you encounter any undesired system behavior
related to functional changes in the new software version.
Operation Description
Get state information You can retrieve information about the update state.
Check for update You can check whether a new update is available.
Get update information You can retrieve information about the available updates.
Get update requirements You can retrieve information about the update requirements.
Note The check phase must have completed successfully before you can stage the
update.
Get staging status You can retrieve information about the status of the stage operation.
Note You must provide the task ID value that you received as a response when you
initiated the stage operation.
Note The update must be staged before you can install it.
Get installation status You can retrieve information about the status of the install operation.
Note You must provide the task ID value that you received as a response when you
initiated the install operation.
Stage and install You can initiate the download of the update and the installation starts when the download
completes.
You can run software update operations by using the vSphere Automation SDK or sending
an HTTP request. You can use interfaces from the com.vmware.appliance.update package to
perform the operations. For more information, see the Java API Reference documentation.
To initiate the update process, you must choose whether the vCenter Server instance should
obtain software updates from a URL or an ISO image. If you use an ISO image to update the
vCenter Server instance, the image must remain attached to the CD/DVD drive of the instance
during the stage and install operations.
The workflow in Figure 13-11. Update Process Workflow describes the standard steps of the
update process.
Start
Check phase
The vCenter Server instance downloads the metadata and scripts.
The vCenter Server instance downloads the data for the components
to be updated. Stage phase
Update phase
End
You can automate checks for new updates and staging of updates by using an update policy. For
example, you can set an update policy to make the vCenter Server instance perform automatic
checks for new updates at midnight every day. If there are new updates available, the vCenter
Server instance can stage them automatically. Using an update policy reduces the waiting time
by automating the first two phases and giving you the option to initiate only the update phase
manually.