先调用获取 X-Subject-Token 接口,再批量创建实例
// 参数
// os password
String password = "123456";
// os user
String user = "root";
// os 的项目id
String projectId = "aaaaa";
// os url
String url = "192.168.119.1xx";
// os imageId
String imageId = "aaa";
// os flavorId
String flavorId = "aaa";
// 批量创建数量
int num = 3;
try {
String body = "{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"name\":\"" + user + "\",\"domain\":{\"name\":\"default\"},\"password\":\"" + password + "\"}}},\"scope\":{\"project\":{\"id\":\"" + projectId + "\"}}}}";
JSONObject objectbody = JSON.parseObject(body);
body = objectbody.toJSONString();
log.info("获取X-Subject-Token");
request.setAttribute("URL", url + ":5000/auth/tokens");
// 自定义 post 发送 http, 获取http header中的 X-Subject-Token
HashMap post = osClientService.post(request, body);
Headers headers = (Headers) post.get("headers");
String token = headers.get("X-Subject-Token");
// 自定义 批量创建 参数
// 定义账号密码 批量创建所有实例密码一致
instancePassword = "123456";
String pass = "#cloud-config\nchpasswd:\n list: |\n root:" + instancePassword + "\n expire: false\nssh_pwauth: true";
String userData = new sun.misc.BASE64Encoder().encode(pass.getBytes()).replace("\r\n", "");
// 定义实例名称 创建单个实例名称不变 多个实例名称后面跟实例序号
String instanceName = "instance-Test";
body = "{\"server\":{\"name\":\"" + instanceName + "\",\"imageRef\":\"" + imageId + "\",\"flavorRef\":\"" + flavorId + "\",\"metadata\":{\"My Server Name\":\"Apache1\"},\"user_data\":\"" + userData + "\",\"max_count\":\"" + num + "\"}}";
JSONObject object = JSON.parseObject(body);
body = object.toJSONString();
request.setAttribute("URL", url + ":8774/v2/servers");
request.setAttribute("X-Auth-Token", token);
// 自定义 post 发送 http 获取http responseBody
HashMap creatVMPost = osClientService.post(request, body);
Object responseBody = creatVMPost.get("responseBody");
ArrayList<String> instanceNames = new ArrayList<>();
} catch (Exception e) {
log.error("创建vm失败:" + e);
result.setErrorMsg("创建vm失败" + e);
result.setErrorCode("-1");
}