从 pod 访问 K8S API

Access K8S API from a pod

我有一个主 pod,它访问并进行 Kubernetes API 调用以部署其他 pods(下面的代码类似)。它工作正常。现在,我不想使用配置文件。我知道可以使用服务帐户。 https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/。如何配置允许我的 pod 访问 APIs 的服务帐户(例如默认服务帐户)?

public class KubeConfigFileClientExample {
  public static void main(String[] args) throws IOException, ApiException {

    // file path to your KubeConfig
    String kubeConfigPath = "~/.kube/config";

    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client =
        ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    System.out.println("Listing all pods: ");
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
}

官方 Java 客户端有 in-cluster client example 的示例。

它与您的代码非常相似,您需要使用不同的 ClientBuilder:

ApiClient client = ClientBuilder.cluster().build();

并像这样使用它:

    // loading the in-cluster config, including:
    //   1. service-account CA
    //   2. service-account bearer-token
    //   3. service-account namespace
    //   4. master endpoints(ip, port) from pre-set environment variables
    ApiClient client = ClientBuilder.cluster().build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();