1

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

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());
    }
  }
}
4

1 回答 1

1

官方 Java 客户端有集群内客户端示例的示例

它与您的代码非常相似,您需要使用不同的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();
于 2021-09-27T15:27:17.853 回答