How to connect to remote kubernetes cluster using k8s java api instead of fabric8 api

1.3k views Asked by At

Iam able to connect to Kubernetes cluster using Fabric8 api with the following code :

            String masterUrl = "<Kube Master Url>";
            Map<String, String> certFileNamesMap = getCertificates();
            Config config = new ConfigBuilder().withMasterUrl(masterUrl).build();
            config.setWebsocketPingInterval(30000L);
            config.setConnectionTimeout(300000);
            config.setRequestTimeout(300000);
            if (certFileNamesMap != null) {
                config.setCaCertFile(certFileNamesMap.get(CA_CERT_FILE));
                config.setClientCertFile(certFileNamesMap.get(CLIENT_CERT_FILE));
                config.setClientKeyFile(certFileNamesMap.get(CLIENT_KEY_FILE));
            }
            KubernetesClient client = new DefaultKubernetesClient(config);

I am able to set the certificates and able to connect to https://MasterIP but with https://github.com/kubernetes-client/java API I'm not able to figure out the way to set the certs as well as remote master IP. Is there anyway to do that with official kubernetes client API? as fabric8 API is officially discontinued by their team.

Im trying with the following code inside container in minikube :

            ApiClient client = ClientBuilder.cluster().build();
            Configuration.setDefaultApiClient(client);
            System.out.println("Loading in app cluster 3");
            CoreV1Api api = new CoreV1Api();
            V1PodList list =
                    api.listPodForAllNamespaces(null,
                            null,
                            null,
                            null,
                            100,
                            null,
                            null,
                            null,
                            null,
                            null);
            System.out.println("Listing all pods: ");
            for (V1Pod item : list.getItems()) {
                System.out.println(item.getMetadata().getName());
            }

Im getting error as forbidden.

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.listPodForAllNamespacesWithHttpInfo(CoreV1Api.java:35956)
at io.kubernetes.client.openapi.apis.CoreV1Api.listPodForAllNamespaces(CoreV1Api.java:35848)
1

There are 1 answers

0
user1188867 On BEST ANSWER

Iam able to figure out the way, we need to use /.kube/config file and copy all the certificates into that file itself, then there is an api in kubernetes java client which reads the config file and gives access to kube cluster.