k8s java client中的示例都使用默认客户端,请参见here。
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);如何配置k8s客户端,以便它可以从k8s集群pod与k8s CRD(例如,sparkoperator)通信?我应该如何配置这个客户端?(basePath,身份验证?)在同一个k8s集群中的pod中,我应该使用什么basePath?
发布于 2019-02-08 22:19:31
您也可以使用defaultClient来实现此目的。
如果应用程序在群集内运行并且具有正确的服务帐户,则defaultClient()方法将创建群集内客户端。
您可以从here方法的注释中看到defaultClient的规则:
/**
* Easy client creation, follows this plan
*
* <ul>
* <li>If $KUBECONFIG is defined, use that config file.
* <li>If $HOME/.kube/config can be found, use that.
* <li>If the in-cluster service account can be found, assume in cluster config.
* <li>Default to localhost:8080 as a last resort.
* </ul>
*
* @return The best APIClient given the previously described rules
*/因此,如果使用k8s java客户端的应用程序运行在它自己的集群上,只要它拥有正确的权限,它就应该能够访问集群上的内容。您需要允许客户端应用程序能够访问CRD,例如CRDs of Prometheus Operator的ClusterRole示例
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: prometheus-crd-view
labels:
rbac.authorization.k8s.io/aggregate-to-admin: "true"
rbac.authorization.k8s.io/aggregate-to-edit: "true"
rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
- apiGroups: ["monitoring.coreos.com"]
resources: ["alertmanagers", "prometheuses", "prometheusrules", "servicemonitors"]
verbs: ["get", "list", "watch"]发布于 2019-02-08 17:58:00
您可以使用Kubernetes API,只需安装curl即可。
curl http://localhost:8080/api/v1/namespaces/default/pods
只需将localhost更改为apiserver ip address/dns name即可
您应该阅读Kubernetes API documentation。
此外,您还需要配置RBAC的访问和权限。集群内的容器使用令牌填充,该令牌用于向API服务器进行身份验证。您可以通过在POD中执行cat /var/run/secrets/kubernetes.io/serviceaccount/token来验证这一点。
这样,您从容器内部向apiserver发出的请求可能如下所示:
curl -ik \
-H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \
https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods您还可以在容器中安装kubectl,还可以设置所需的权限see this for more details。
我推荐阅读下面的Installing kubectl in a Kubernetes Pod和The Kubernetes API call is coming from inside the cluster!
至于其他Java客户端,还有一些非官方的客户端库,比如Java (OSGi)和Java (Fabric8, OSGi)。
https://stackoverflow.com/questions/54580380
复制相似问题