yaml创建
client-java创建
本质上就是用代码创建一个包含了yaml中必要的参数的对象调用接口来进行创建。
使用AppsV1Api apiInstance = new AppsV1Api()下的createNamespacedDeployment接口
@Data
public class DeploymentDTO {
private String namespace;
private String deploymentName;
private Integer replicas;
private String metadataLabelsApp;
private String image;
private String portName;
private Integer containerPort;
}
public ApiClient getConnection() {
ApiClient client = new ClientBuilder().
setBasePath(https://192.168.2.3:6443).
setVerifyingSsl(false).
setAuthentication(new AccessTokenAuthentication(token)). // 自己去获取token,通过安装kuboard或dashboard可以获取
build();
Configuration.setDefaultApiClient(client);
return client;
}
/**
* 创建一个deployment
* @param deploymentDTO
* @return
*/
@PostMapping("/createNamespacedDeployment")
public ResultUtil createNamespacedDeployment(@RequestBody DeploymentDTO deploymentDTO) {
Gson gson = new Gson();
AppsV1Api apiInstance = new AppsV1Api(k8sInit.getConnection());
V1Deployment result;
// labels
Map<String,String> matchLabels = new HashMap<>();
matchLabels.put("app", deploymentDTO.getMetadataLabelsApp());
// ports
List<V1ContainerPort> portList = new ArrayList<>();
V1ContainerPort port = new V1ContainerPort();
port.setName(deploymentDTO.getPortName());
port.setContainerPort(81);
portList.add(port);
// 使用对象封装deployment
V1Deployment body = new V1DeploymentBuilder()
.withApiVersion("apps/v1")
.withKind("Deployment")
.withNewMetadata()
.withName(deploymentDTO.getDeploymentName())
.withNamespace(deploymentDTO.getNamespace())
.endMetadata()
.withNewSpec()
.withReplicas(deploymentDTO.getReplicas())
.withNewSelector()
.withMatchLabels(matchLabels)
.endSelector()
.withNewTemplate()
.withNewMetadata()
.withLabels(matchLabels)
.endMetadata()
.withNewSpec()
.withContainers(
new V1Container()
.name(deploymentDTO.getMetadataLabelsApp())
.image(deploymentDTO.getImage())
.imagePullPolicy("IfNotPresent")
.ports(portList)
)
.endSpec()
.endTemplate()
.endSpec()
.build();
try {
result = apiInstance.createNamespacedDeployment(
deploymentDTO.getNamespace(),
body,
"true",
null,
null);
System.out.println(result);
} catch (ApiException e) {
return ResultUtil.error(String.valueOf(e.getCode()), e.getMessage());
}
return ResultUtil.success(gson.toJson(result));
}
postman请求
地址
http://localhost:8080/api/v1/deployment/createNamespacedDeployment/
参数
{
"namespace": "default",
"deploymentName": "create-deployment-test",
"replicas": 1,
"metadataLabelsApp": "nginx-test",
"image": "nginx:1.7.9",
"portName": "httpd",
"containerPort": 81
}
kuboard上查看的结果
参考
创建时必要的参数