线程“主”io.kubernetes.client.openapi.ApiException 中出现异常:Forbidden

问题描述 投票:0回答:1

我正在使用 Kubernetes java 客户端使用以下代码在 Kubernetes 集群中创建基本 Pod:

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.Config;

public class CreatePodExample {

    public static void main(String[] args) throws ApiException, Exception {
        // Load Kubernetes configuration from default location
        ApiClient client = Config.fromCluster();
        //Configuration.setDefaultApiClient(client);

        // Create CoreV1Api instance
        CoreV1Api api = new CoreV1Api(client);

        // Define metadata for the pod
        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.name("private-hello-container-test");

        // Define container spec for the pod
        V1Container container = new V1ContainerBuilder()
                .withName("private-hello-container-test")
                .withImage("test.azurecr.io/test/app:dev")
                .withImagePullPolicy("IfNotPresent")
                .withCommand("/bin/sh", "-c", "echo hello world!!")
                .build();

        // Define pod spec
        V1Pod pod = new V1PodBuilder()
                .withMetadata(metadata)
                .withNewSpec()
                .addToContainers(container)
                .endSpec()
                .build();

        // Create the pod
        V1Pod createdPod = api.createNamespacedPod("default", pod, null, null, null);
        System.out.println("Pod created: " + createdPod.getMetadata().getName());
    }
}

但出现以下错误:

Exception in thread "main" io.kubernetes.client.openapi.ApiException: Forbidden
        at io.kubernetes.client.openapi.ApiClient.handleResponse(ApiClient.java:993)
        at io.kubernetes.client.openapi.ApiClient.execute(ApiClient.java:905)
        at io.kubernetes.client.openapi.apis.CoreV1Api.createNamespacedPodWithHttpInfo(CoreV1Api.java:9907)
        at io.kubernetes.client.openapi.apis.CoreV1Api.createNamespacedPod(CoreV1Api.java:9873)
        at CreatePodExample.main(CreatePodExample.java:39)

我在这里和那里尝试了一些东西,但没有运气。我该如何解决?

java kubernetes
1个回答
0
投票

我能够解决这个问题。问题出在服务帐户权限上。以下是已解决的权限。

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: job-creator
rules:
- apiGroups: [""]
  resources: ["jobs", "pods"]
  verbs: ["create", "get", "list", "watch"]
- apiGroups: ["batch"]
  resources: ["jobs", "pods"]
  verbs: ["create", "get", "list", "watch"]
© www.soinside.com 2019 - 2024. All rights reserved.