Home > OS >  How to pull values out of kubernetes config into a web application
How to pull values out of kubernetes config into a web application

Time:10-16

I'm looking to create a small web application that lists some data about the ingresses in my cluster. The application will be hosted in the cluster itself, so I assume i'm going to need a service account attached to a backend application that calls the kubernetes api to get the data, then serves that up to the front end through a GET via axios etc. Am I along the right lines here?

CodePudding user response:

You can use the JavaScript Kubernetes Client package for node directly in you node application to access kubeapi server over REST APIs

npm install @kubernetes/client-node

You can use either way to provide authentication information to your kubernetes client

This is a code which worked for me

const k8s = require('@kubernetes/client-node');

const cluster = {
  name: '<cluster-name>',
  server: '<server-address>',
  caData: '<certificate-data>'
};

const user = {
  name: '<cluster-user-name>',
  certData: '<certificate-data>',
  keyData: '<certificate-key>'
};

const context = {
  name: '<context-name>',
  user: user.name,
  cluster: cluster.name,
};

const kc = new k8s.KubeConfig();
kc.loadFromOptions({
  clusters: [cluster],
  users: [user],
  contexts: [context],
  currentContext: context.name,
});

const k8sApi = kc.makeApiClient(k8s.NetworkingV1Api);
k8sApi.listNamespacedIngress('<namespace>').then((res) => {
  console.log(res.body);
});

You need to Api client according to your ingress in my case I was using networkingV1Api

You can get further options from https://github.com/kubernetes-client/javascript

CodePudding user response:

JS client : https://github.com/kubernetes-client/javascript

If you have different ways to authenticate as you mentioned service account that is also one of them.

Yes, you will require it however if you are planning to run your script on cluster only there is no requirement of it.

you can directly use the method to authenticate

const kc = new k8s.KubeConfig()
    kc.loadFromDefault()

    const k8s = require('@kubernetes/client-node')
    const kc = new k8s.KubeConfig()
    kc.loadFromDefault()
    
    const k8sApi = kc.makeApiClient(k8s.NetworkingV1beta1Api) // before 1.14 use extensions/v1beta1
    k8sApi.listNamespacedIngress('<Namespace name>').then((res) => {
  console.log(res.body);
});

You can check out this examples : https://github.com/kubernetes-client/javascript/tree/master/examples you can also use typescript.

  • Related