I'm creating Java API client to connect to a cluster and list the pods,but I'm getting the "Unauthorized" exception every time I try to execute it.
Here is my local project:
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.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader("/Users/stefan.marjanovic/.kube/config"))).build();
Configuration.setDefaultApiClient(client);
CoreV1Api api = new CoreV1Api();
V1PodList list = null;
try {
list = api.listPodForAllNamespaces(null, null, null,
null, null, null, null,
null, null, null);
} catch (ApiException e) {
System.out.println("RESPONSE BODY: " + e.getResponseBody());
System.out.println("MESSAGE: " + e.getMessage());
System.out.println("RESPONSE HEADERS: " + e.getResponseHeaders());
System.out.println("TO STRING: " + e.toString());
e.printStackTrace();
}
for (V1Pod item : list.getItems()) {
System.out.println(item.getMetadata().getName());
}
}
}
And here are the exceptions I get:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
RESPONSE BODY: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}
MESSAGE:
RESPONSE HEADERS: {audit-id=[84b2b2fd-416e-4b83-b1a8-7e499824b8aa], cache-control=[no-cache, private], content-length=[129], content-type=[application/json], date=[Fri, 16 Sep 2022 08:48:16 GMT]}
TO STRING: io.kubernetes.client.openapi.ApiException:
io.kubernetes.client.openapi.ApiException:
at io.kubernetes.client.openapi.ApiClient.handleResponse(ApiClient.java:973)
at io.kubernetes.client.openapi.ApiClient.execute(ApiClient.java:885)
at io.kubernetes.client.openapi.apis.CoreV1Api.listPodForAllNamespacesWithHttpInfo(CoreV1Api.java:37904)
at io.kubernetes.client.openapi.apis.CoreV1Api.listPodForAllNamespaces(CoreV1Api.java:37797)
at Example.main(Example.java:48)
Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:58)
I'm basically trying to do the same stuff at work, but instead of kubeconfig file, I'm using ApiClient client = ClientBuilder.cluster().build(); to generate client.
Any help? Thanks!