如何配置k8s客户端,以便它可以与k8s集群Pod中的k8s CRD对话?

时间:2019-02-07 18:56:43

标签: kubernetes google-api-java-client kubernetes-ingress kubernetes-pod

k8s Java客户端中的示例均使用默认客户端,请参见here

ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);

我如何配置k8s客户端,以便它可以与k8s集群Pod中的k8s CRD(例如,sparkoperator)对话?我应该如何配置此客户端? (basePath,身份验证?)在同一k8s集群中的pod中应该使用什么basePath?

2 个答案:

答案 0 :(得分:1)

您也可以使用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 OperatorClusterRole的示例:

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"]

答案 1 :(得分:0)

您可以使用Kubernetes API,只需安装curl。

curl http://localhost:8080/api/v1/namespaces/default/pods

只需将localhost更改为apiserver ip address / dns name

您应该阅读Kubernetes API documentation

此外,您将需要配置RBAC的访问和权限。 群集中的容器填充有用于对API服务器进行身份验证的令牌。 您可以通过在cat /var/run/secrets/kubernetes.io/serviceaccount/token内执行POD来验证。

这样,您从容器内部对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 PodThe Kubernetes API call is coming from inside the cluster!

与其他Java客户端一样,还有非官方客户端库,例如Java (OSGi)Java (Fabric8, OSGi)

相关问题