使用开源sdk vijava (http://vijava.sourceforge.net/)
1.创建数据中心
String vCenterAddress = "172.16.211.31";
String vCenterUserName = "administrator";
String vCenterPassword = "P@ssw0rd!";
//建立到vCenter 的链接
ServiceInstance si = new ServiceInstance(new URL("https://"
+ vCenterAddress + "/sdk"), vCenterUserName, vCenterPassword,
true);
String datacenterName = "Test-Datacenter";
//创建数据中心
Datacenter dc = si.getRootFolder().createDatacenter(datacenterName);
2.在数据中心中添加集群
String clusterName = "Test-Cluster";
//在新创建的数据中心下创建集群
ClusterConfigSpecEx clusterSpec = new ClusterConfigSpecEx();
ClusterComputeResource cluster = dc.getHostFolder().createClusterEx(clusterName, clusterSpec );
3.在数据中心中添加ESXi主机
HostConnectSpec hostSpec = new HostConnectSpec();
String userName = "root";
String password = "password";
String host ="172.16.210.111";
hostSpec.setUserName(userName);
hostSpec.setPassword(password);
hostSpec.setHostName(host);
hostSpec.setForce(true); // forcely take over the host
//添加主机到集群中
Task morTask = cluster.addHost_Task(hostSpec, true, null, null);
String taskResult = morTask.waitForTask();
if (!Task.SUCCESS.equalsIgnoreCase(taskResult)) {
throw new RuntimeException("Unable to add host " + host
+ " to vSphere cluster due to " + taskResult);
}
全部代码:
String vCenterAddress = "172.16.211.31";
String vCenterUserName = "administrator";
String vCenterPassword = "P@ssw0rd!";
ServiceInstance si = new ServiceInstance(new URL("https://"
+ vCenterAddress + "/sdk"), vCenterUserName, vCenterPassword,
true);
String datacenterName = "Test-Datacenter";
//创建数据中心
Datacenter dc = si.getRootFolder().createDatacenter(datacenterName);
String clusterName = "Test-Cluster";
//在新创建的数据中心下创建集群
ClusterConfigSpecEx clusterSpec = new ClusterConfigSpecEx();
ClusterComputeResource cluster = dc.getHostFolder().createClusterEx(clusterName, clusterSpec );
HostConnectSpec hostSpec = new HostConnectSpec();
String userName = "root";
String password = "password";
String host ="172.16.210.111";
hostSpec.setUserName(userName);
hostSpec.setPassword(password);
hostSpec.setHostName(host);
hostSpec.setForce(true); // forcely take over the host
//添加主机到集群中
Task morTask = cluster.addHost_Task(hostSpec, true, null, null);
String taskResult = morTask.waitForTask();
if (!Task.SUCCESS.equalsIgnoreCase(taskResult)) {
throw new RuntimeException("Unable to add host " + host
+ " to vSphere cluster due to " + taskResult);
}