how can I load configuration for kubernetes using kubernetes-client. Google Cloud

Viewed 1740

I have TS application that uses kubernetes-client library to connect to kubernetes in Google Cloud.

import { KubeConfig, CoreV1Api } from "@kubernetes/client-node";
const kc = new KubeConfig();
kc.loadFromDefault();
const kbsCoreApi = kc.makeApiClient(CoreV1Api);

When running locally works great, but when I dockerize it, it does not work due to not knowing how to load configuration. I tried to create a config file and load it using "kc.loadFromFile('~/some/path')" instead but It seems that I am missing something it gives me a HTTP error. Here is my configuration file.

    {
  "kind": "Config",
  "apiVersion": "v1",
  "clusters": [
    {
      "name": "cluster1",
      "cluster": {
        "certificate-authority-data": "cert-data",
        "server": "https://128.1.1.2"
      }
    }
  ],
  "users": [
    {
      "name": "cluster1",
      "user": {
        "password": "myPassword",
        "usernmae": "myUsername"
      }
    }
  ],
  "contexts": [
    {
      "name": "cluster1",
      "context": {
        "cluster": "cluster1",
        "user": "cluster1"
      }
    }
  ],
  "current-context": "cluster1"
}
1 Answers

Use kc.loadFromCluster(); instead of the kc.loadFromDefault(); used in your code.

See in-cluster example

When starting the client with the in-cluster authentication, it will use the ServiceAccount token on /var/run/secrets/kubernetes.io/serviceaccount

Also make sure that this ServiceAccount has the RBAC permissions for the resource operations that your client code use. But you should be able to get proper error messages, unless.

Related