I have a main pod that accesses and makes Kubernetes API calls to deploy other pods (the code similar below). It works fine. Now, I don't want to use the config file. I know it's possible with a service account. https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/. How do I configure a service account (e.g default service account) that allows my pod to access the APIs?
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());
}
}
}
The official Java client has example for in-cluster client example.
It is quite similar to your code, you need to use a different ClientBuilder:
ApiClient client = ClientBuilder.cluster().build();
and use it like this:
// 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();