Jonas
Jonas

Reputation: 7925

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?

Upvotes: 3

Views: 2305

Answers (1)

matt_j
matt_j

Reputation: 4614

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
...

Upvotes: 6

Related Questions