Search code examples
javaamazon-web-serviceskubernetesfabric8

How to connect to an existing kubernetes server and list all pods using java?


I'm trying to connect to an existing kubernetes that's running on AWS and run arbitrary commands on it using Java. Specifically, we are using fabric8 (although I am open to another api if you can provide a sufficient answer using one). The reason I need to do this in Java is because we plan to eventually incorporate this into our existing junit live tests.

For now I just need an example of how to connect to the sever and get all of the pod names as an array of Strings. Can somebody show me a simple, concise example of how to do this.

i.e. I want the equivalent of this bash script using a java api (again preferably using fabric8, but I'll accept another api if you know one)

#!bin/bash
kops export kubecfg --name $CLUSTER --state=s3://$STATESTORE

kubectl get pod -o=custom-colums=NAME:.metadata.name -n=$NAMESPACE

Solution

  • Here is the fabric8 kubernetes client for kubernetes:

    https://github.com/fabric8io/kubernetes-client/

    It comes with a fluent DSL to work with kubernetes/Openshift resources. It has got pagination support too. If you want to list resources in certain namespace then you can use inNamespace("your namespace") parameter in dsl.

    String master = "https://192.168.42.20:8443/";
    
    Config config = new ConfigBuilder().withMasterUrl(master).build();
    try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
      // Simple Listing:
      PodList simplePodList = client.pods().inAnyNamespace().list();      
    
      // List with limit and continue options:
      PodList podList = client.pods().inAnyNamespace().list(5, null);
      podList.getItems().forEach((obj) -> { System.out.println(obj.getMetadata().getName()); });
    
      podList = client.pods().inAnyNamespace().list(5, podList.getMetadata().getContinue());
      podList.getItems().forEach((obj) -> { System.out.println(obj.getMetadata().getName()); });
    
    } catch (KubernetesClientException e) {
      logger.error(e.getMessage(), e);
    }