参考连接 github: https://github.com/kubernetes-client/java/
初次使用 : 测试连接
导入kubernetes-client包
<!--kubernetes--><dependency><groupId>io.kubernetes</groupId><artifactId>client-java</artifactId><version>17.0.0</version></dependency>
由于使用gke(google cloud kubernetes)不好获取kubernetes的配置文件,且程序要在kubernetes集群内运行,所以直接使用examples 中的InClusterClientExample 的例子测试是否连通
//这里默认获取的是程序运行所在命名空间下的default账户
ApiClient client = ClientBuilder.cluster().build();Configuration.setDefaultApiClient(client);// the CoreV1Api loads default api-client from global configuration.
CoreV1Api api = new CoreV1Api();// invokes the CoreV1Api client//这里官方给的例子是listPodForAllNamespaces
//获取所有命名空间下的pod 但是我的default这里会没有所有命名空间权限
//可以修改为api.listNamespacedPod(),namespace 填写“default”
V1PodList list =
api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null, null);
for (V1Pod item : list.getItems()) {System.out.println(item.getMetadata().getName());
}
代码来源 : https://github.com/kubernetes-client/java/blob/master/examples/examples-release-15/src/main/java/io/kubernetes/client/examples/InClusterClientExample.java
如上面所述,default缺少很多权限,即使将listPodForAllNamespaces()替换成listNamespacedPod() default服务账号还是会由于缺少pod访问权限 出现ApiException
提示信息如下:
Response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"pods is forbidden: User "system:serviceaccount:default:default" cannot list resource "pods" in API group "" at the cluster scope","reason":"Forbidden","details":{"kind":"pods"},"code":403}
所以现在需要为服务账户 default 授予访问 Pod 资源的权限。使用 Role 和 RoleBinding 对象来授予服务账户所需的权限
编写rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:name: pod-reader
rules:
- apiGroups: [""]resources: ["pods"]verbs: ["get", "list", "watch"]---apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:name: read-pods
roleRef:apiGroup: rbac.authorization.k8s.iokind: Rolename: pod-reader
subjects:
- kind: ServiceAccountname: defaultnamespace: default
这里创建了一个role对象,拥有pod资源的get,list watch 的权限,并且创建了一个RoleBinding对象将role对象绑定到服务账号default上,从而授予它访问pod资源的权限。
使用kuberctl apply命令:
kubectl apply -f rbac.yaml
就可以通过代码读取default命名空间下的pod信息了。
完成功能 :通过代码创建job
public void createJob(String jobName,String image,List<String> commend,String containName,Map<String,String> nodeSelector,Map<String, Quantity> resourceLimits,Map<String, Quantity> resourceRequests) {ApiClient client = null;try {client = ClientBuilder.cluster().build();} catch (IOException e) {;throw new RuntimeException(e);}Configuration.setDefaultApiClient(client);V1Volume v1Volume = new V1Volume().name(config.getVolumeName()).persistentVolumeClaim(new V1PersistentVolumeClaimVolumeSource().claimName(config.getVolumeName()));V1VolumeMount v1VolumeMount = new V1VolumeMount();v1VolumeMount.setMountPath(config.getVolumeMountPath());v1VolumeMount.setName(config.getVolumeName());V1ResourceRequirements resources = new V1ResourceRequirements().limits(resourceLimits).requests(resourceRequests);V1Job job = new V1Job();job.setMetadata(new V1ObjectMeta().name(jobName));job.setSpec(new V1JobSpec().backoffLimit(1).template(new V1PodTemplateSpec().spec(new V1PodSpec().addVolumesItem(v1Volume).addContainersItem(new V1Container().addVolumeMountsItem(v1VolumeMount).name(containName).image(image).command(commend).resources(resources)).nodeSelector(nodeSelector).restartPolicy("Never"))));try {BatchV1Api batchApi = new BatchV1Api();V1Job createdJob = batchApi.createNamespacedJob("default", job, null, null, null,null);log.info("Created Job: {}" , createdJob.getMetadata().getName());} catch (ApiException e) {log.error("Kubernetes API returned an error:");log.error("Code: {}", e.getCode());log.error("Response body: {}", e.getResponseBody());log.error("Message: {}", e.getMessage());e.printStackTrace();}}
编写授权default服务账号创建job权限的rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:name: job-creator
rules:
- apiGroups: ["batch"]resources: ["jobs"]verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]---apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:name: create-jobs
roleRef:apiGroup: rbac.authorization.k8s.iokind: Rolename: job-creator
subjects:
- kind: ServiceAccountname: defaultnamespace: default
运行命令 : kubectl apply -f rbac.yaml