【问题标题】:How to config k8s client so that it can talk to k8s CRDs from a k8s cluster pod?如何配置 k8s 客户端,以便它可以与 k8s 集群 pod 中的 k8s CRD 通信?
【发布时间】:2019-02-07 18:56:43
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    您也可以使用defaultClient

    如果应用程序在集群内运行并且具有正确的服务帐户,defaultClient() 方法将创建一个集群内客户端。

    您可以在方法here 上从cmets 中查看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,例如 ClusterRole for CRDs of Prometheus Operator 的示例:

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

    【讨论】:

      【解决方案2】:

      你可以使用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 PodThe Kubernetes API call is coming from inside the cluster!

      至于其他 Java 客户端,也有 非官方 客户端库,例如 Java (OSGi)Java (Fabric8, OSGi)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-30
        • 2018-10-18
        • 1970-01-01
        • 2020-06-07
        • 2021-08-19
        • 2019-01-20
        • 2022-07-28
        • 2021-12-25
        相关资源
        最近更新 更多