Sunday, 25 June 2017

Accessing the Kubernetes API Server From The Pod.

Kubernetes API server can be access from the pod on the following URL, https://kubernetes.default .

To get authenticated for accessing the api server url, we also need to pass the service account token and the "ca cert". Once that is done, we can perform all the operations that are permitted to that service account.

Let's say, suppose we have deployed our code as a POD in the kubernetes cluster, and the same code is responsible for creating other stateful sets /replica sets / services / namespaces. In that case we will required to get authenticated for accessing the api server.  And using kubernetes-client, we can deploy our deployment.

I am using the godaddy-kubernetes-client library for creating namespaces , deployments and statefulsets.

The "token" and "ca cert" resides at the following location in the pod :

a. token : /var/run/secrets/
b. ca-cert : /var/run/secrets/

let getRequestInfo = () => {
    return {
        url: "https://kubernetes.default",
        ca:   fs.readFileSync('/var/run/secrets/').toString(),
        auth: {
            bearer: fs.readFileSync('/var/run/secrets/').toString(),
        timeout: 1500

let initK8objs = () =>{
    k8obj = getRequestInfo();
    k8score = new Api.Core(k8obj),
    k8s = new Api.Api(k8obj);

And once the authentication is done, we can use the above created k8score and k8s object to perform crud operations on the API server.

ex :"v1").ns().post('/json-path')  will create a new namespace.

And the other way of authenticating is passing the cluster username and password with the "ca-cert" also known as basic authentication, In the below case we will need to pass the user and password to the pod by either environment variables or using secrets.

const core = new Api.Core({
  url: 'https://kubernetes.default',
  ca: fs.readFileSync('cluster-ca.pem'),
  auth: {
    user: 'user',
    pass: 'pass'