How to connect to DigitalOcean Kubernetes cluster from Java?

9/16/2019

I have a Kubernetes cluster on DigitalOcean, and I try to list the pods in it using Kubernetes Java API.

String kubeConfigPath = "~/.kube/config";

KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath));

ApiClient client = ClientBuilder
        .kubeconfig(config)
        .build();

Configuration.setDefaultApiClient(client);

CoreV1Api api = new CoreV1Api();

V1PodList list = api.listNamespacedPod("default", true, null,
        null, null, null,
        null, null, null,
        null
);

for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
}

But when I run it, I get the following error

Exception in thread "main" io.kubernetes.client.ApiException: Forbidden
    at io.kubernetes.client.ApiClient.handleResponse(ApiClient.java:886)
    at io.kubernetes.client.ApiClient.execute(ApiClient.java:802)
    at io.kubernetes.client.apis.CoreV1Api.listNamespacedPodWithHttpInfo(CoreV1Api.java:16949)
    at io.kubernetes.client.apis.CoreV1Api.listNamespacedPod(CoreV1Api.java:16926)
    at com.workfront.k8s.KubeConfigFileClientExample.main(KubeConfigFileClientExample.java:30)

When I use minikube, it works fine.

-- Carmine
kubernetes

0 Answers