<h1>Context</h1>
<p>I have a java application built as a docker image.</p>
<p>The image is deployed in a k8s cluster.</p>
<p>In the java application, I want to connect to the api server and save something in Secrets.</p>
<p>How can I do that with k8s java client?</p>
<h1>Current Attempts</h1>
<p>The <a href="https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#accessing-the-api-from-a-pod" rel="nofollow noreferrer">k8s official document</a> says:</p>
<blockquote>
<p>From within a pod the recommended ways to connect to API are:</p>
<ul>
<li>run kubectl proxy in a sidecar container in the pod, or as a background process within the container. This proxies the Kubernetes API to the localhost interface of the pod, so that other processes in any container of the pod can access it.</li>
<li>use the Go client library, and create a client using the rest.InClusterConfig() and kubernetes.NewForConfig() functions. They handle locating and authenticating to the apiserver.</li>
</ul>
</blockquote>
<p>But I can't find similar functions neither similar examples in java client.</p>

kevin807210561
<p>With the assumption that your Pod has a <code>serviceAccount</code> automounted -- which is the default unless you have specified otherwise -- the <a href="https://github.com/kubernetes-client/java/blob/client-java-parent-2.0.0/util/src/main/java/io/kubernetes/client/util/ClientBuilder.java#L119" rel="nofollow noreferrer"><code>ClientBuilder.cluster()</code></a> method reads the API URL from the environment, reads the cluster CA from the well known location, and similarly the <code>ServiceAccount</code> token from that same location.</p>

<p>Then, while not exactly "create a Secret," this <a href="https://github.com/kubernetes-client/java/blob/client-java-parent-2.0.0/examples/src/main/java/io/kubernetes/client/examples/PatchExample.java" rel="nofollow noreferrer"><code>PatchExample</code></a> performs a mutation operation which one could generalize into "create or update a Secret."</p>
