Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Kubernetes Client: List and Read Custom Resource Definition

I'm using the Javascript Kubernetes Client and I'm trying to read all resources from a custom resource definition. In particular I want to run kubectl get prometheusrule (prometheusrule is my CRD).

I couldn't find a wat to do this yet. I can read resources like this:

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

const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

k8sApi.listNamespacedPod('default').then((res) => {
    res.body.items.forEach(pod => console.log(pod.metadata.name));
});

But it does not provide a method for reading CRDs.

I also tried

const k8Client = k8s.KubernetesObjectApi.makeApiClient(kc);
k8Client.read({ kind: "service"}).then(res => console.log(res));

But this way I get the error UnhandledPromiseRejectionWarning: Error: Unrecognized API version and kind: v1 service

Any idea how I can achieve this?

like image 586
Jonas Avatar asked Dec 04 '25 13:12

Jonas


1 Answers

You can use the listNamespacedCustomObject function. This function has four required arguments as described below:

  • group - the custom resource's group name
  • version - the custom resource's version
  • namespace - the custom resource's namespace
  • plural - the custom resource's plural name.

I've created a sample script that lists all PrometheusRules to illustrate how it works:

$ cat list_rules.js
const k8s = require('@kubernetes/client-node')
const kc = new k8s.KubeConfig()
kc.loadFromDefault()

const k8sApi = kc.makeApiClient(k8s.CustomObjectsApi)

k8sApi.listNamespacedCustomObject('monitoring.coreos.com','v1','default', 'prometheusrules').then((res) => {
    res.body.items.forEach(rule => console.log(rule.metadata.name));
});

We can check if it works as expected:

$ node list_rules.js
prometheus-kube-prometheus-alertmanager.rules
prometheus-kube-prometheus-etcd
prometheus-kube-prometheus-general.rules
prometheus-kube-prometheus-k8s.rules
...
like image 179
matt_j Avatar answered Dec 07 '25 13:12

matt_j



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!