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?
You can use the listNamespacedCustomObject function. This function has four required arguments as described below:
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With