【问题标题】:Access K8S API from a pod从 pod 访问 K8S API
【发布时间】:2021-11-19 18:05:34
【问题描述】:

我有一个主 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());
    }
  }
}

【问题讨论】:

    标签: java kubernetes kubernetes-pod k8s-serviceaccount


    【解决方案1】:

    官方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();
    

    【讨论】:

    • 我需要为“默认”服务帐户配置或添加角色吗?
    • 是的,您会收到错误,错误消息会描述您缺少哪些权限。
    • 我在下面看到错误。如何向默认服务帐户添加权限? "失败", "消息", "服务被禁止: 用户 "system:serviceaccount:default:default" 不能在命名空间 "default" "的 API 组 " 中创建资源 "services" ","re​​ason":"Forbidden"," details":{"kind":"services"},"code":403} :"Failure","message":"deployments.apps 被禁止:用户“system:serviceaccount:default:default”无法创建资源“deployments” " 在命名空间中的 API 组 "apps" "default"","re​​ason":"Forbidden","details":{"group":"apps","kind":"deployments"},"code":403 }
    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2022-01-18
    • 2020-05-30
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多