How can a Java application running in a GKE cluster programatically apply a yaml file?

4/8/2020

I have a Java application deployed on a Google Kubernetes Engine cluster. How can I make this application programmatically apply a yaml? Something equivalent to

kubectl apply -f deployment.yaml

I came across this client library but can't find a part of the documentation that shows how to achieve it. https://github.com/googleapis/google-api-java-client-services/tree/master/clients/google-api-services-container/v1

Edit:

Thanks Guillaume and Mickey for the pointers. I tried the Kubernetes Java Client library but got 'Forbidden'. See the code below and response:

    @RequestMapping(value = "/list-pods", method = GET, produces = TEXT_PLAIN_VALUE)
    public String listPods() throws Exception {
        KubeConfig.registerAuthenticator(new GCPAuthenticator());
        final CoreV1Api api = new CoreV1Api(Config.defaultClient());
        V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
        StringBuilder builder = new StringBuilder("Pods: \n\n");
        for (V1Pod item : list.getItems()) builder.append(item.getMetadata().getName());
        return builder.toString();
    }

This is the exception that was thrown:

2020-04-10 07:52:46.655 ERROR 1 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is io.kubernetes.client.ApiException: Forbidden] with root cause

io.kubernetes.client.ApiException: Forbidden
        at io.kubernetes.client.ApiClient.handleResponse(ApiClient.java:886) ~[client-java-5.0.0.jar!/:na]
        at io.kubernetes.client.ApiClient.execute(ApiClient.java:802) ~[client-java-5.0.0.jar!/:na]
        at io.kubernetes.client.apis.CoreV1Api.listPodForAllNamespacesWithHttpInfo(CoreV1Api.java:18720) ~[client-java-api-5.0.0.jar!/:na]
        at io.kubernetes.client.apis.CoreV1Api.listPodForAllNamespaces(CoreV1Api.java:18698) ~[client-java-api-5.0.0.jar!/:na]
        at com.ngserve.clapps.ws.WS.listPods(WS.java:53) ~[classes!/:0.0.1-SNAPSHOT]
-- scaihai
google-cloud-platform
google-kubernetes-engine
java
kubernetes

1 Answer

4/10/2020

I finally got it to work by configuring the necessary rbac as FL3SH suggested. https://kubernetes.io/docs/reference/access-authn-authz/rbac/

-- scaihai
Source: StackOverflow