This example is based on the code in the CreateDefaultVM.java and PlacementHelper.java sample files.
Note: For a complete and up-to-date version of the Java sample code, see the
vsphere-automation-sdk-java VMware repository at GitHub.
... private static final String DEFAULT_VM_NAME = "Sample-Default-VM"; private VM vmService; private GuestOS vmGuestOS = GuestOS.WINDOWS_9_64; private String defaultVMId; ... public VMTypes.PlacementSpec getPlacementSpecForCluster( StubFactory stubFactory, StubConfiguration sessionStubConfig, String datacenterName, String clusterName, String vmFolderName, String datastoreName) { String clusterId = ClusterHelper.getCluster(stubFactory, sessionStubConfig, datacenterName, clusterName); System.out.println("Selecting cluster " + clusterName + "(id=" + clusterId + ")"); String vmFolderId = FolderHelper.getFolder(stubFactory, sessionStubConfig, datacenterName, vmFolderName); System.out.println("Selecting folder " + vmFolderName + "id=(" + vmFolderId + ")"); 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; } private void createDefaultVM() { VMTypes.PlacementSpec vmPlacementSpec = this.getPlacementSpecForCluster( this.vapiAuthHelper.getStubFactory(), this.sessionStubConfig, this.datacenterName, this.clusterName, this.vmFolderName, this.datastoreName); VMTypes.CreateSpec vmCreateSpec = new VMTypes.CreateSpec.Builder(this.vmGuestOS) .setName(DEFAULT_VM_NAME) .setPlacement(vmPlacementSpec) .build(); ... }