Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patch K8s Custom Resource with @kubernetes/client-node

I'm building Istio/K8s-based platform for controlling traffic routing with NodeJS. I need to be able to programmatically modify Custom Resources and I'd like to use the @kubernetes/node-client for that. I wasn't able to find the right API for accessing Custome Resources in docs and the repo. Am I missing something? Thx in adv.

EDIT: When using CustomObjectApi.patchNamespacedCustomObject function, I'm getting the following error back from K8s API:

message: 'the body of the request was in an unknown format - accepted media types include: application/json-patch+json, application/merge-patch+json, application/apply-patch+yaml', reason: 'UnsupportedMediaType', code: 415

My Code:

const k8sYamls = `${path.resolve(path.dirname(__filename), '..')}/k8sYamls`
const vServiceSpec = read(`${k8sYamls}/${service}/virtual-service.yaml`)
const kc = new k8s.KubeConfig()
kc.loadFromDefault()
const client = kc.makeApiClient(k8s.CustomObjectsApi)
const result = await client.patchNamespacedCustomObject(vServiceSpec.apiVersion.split('/')[0], vServiceSpec.apiVersion.split('/')[1], namespace, 'virtualservices', vServiceSpec.metadata.name, vServiceSpec)

virtual-service.yaml:

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: message-service
spec:
  hosts:
  - message-service
  http:
  - name: 'production'
    route:
    - destination:
        host: message-service
      weight: 100
    retries:
      attempts: 3
      perTryTimeout: 2s
      retryOn: 5xx
like image 450
Aleksander Nowak Avatar asked May 06 '26 04:05

Aleksander Nowak


1 Answers

I was using the wrong type for the body object in that method. I got it to work following this example.

const patch = [
  {
    "op": "replace",
    "path":"/metadata/labels",
    "value": {
      "foo": "bar"
    }
  }
];
const options = { "headers": { "Content-type": k8s.PatchUtils.PATCH_FORMAT_JSON_PATCH}};
k8sApi.patchNamespacedPod(res.body.items[0].metadata.name, 'default', patch, undefined, undefined, undefined, undefined, options)
  .then(() => { console.log("Patched.")})
  .catch((err) => { console.log("Error: "); console.log(err)});
like image 135
Aleksander Nowak Avatar answered May 08 '26 17:05

Aleksander Nowak



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!