How to use the @kubernetes/client-node.KubeConfig function in @kubernetes/client-node

To help you get started, we’ve selected a few @kubernetes/client-node examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sandstorm / metacontroller-framework / src / index.ts View on Github external
validateKubernetesResources(singleOperatorName) {
            // 1) Delete/Create Namespace. NOTE: for some reason, we need to do this using the Kubectl Command Line;
            //    as I was not able to wait on the deleted namespace using the Kubernetes JS client.
            execSync("kubectl delete namespace metacontroller-dev || echo 'Namespace does not exist'", { stdio: 'inherit' });
            execSync("kubectl create namespace metacontroller-dev", { stdio: 'inherit' });

            const kc = new k8s.KubeConfig();
            kc.loadFromDefault();
            const k8sApi_apiExtensions = kc.makeApiClient(k8s.Apiextensions_v1beta1Api);
            const k8sApi_customObjects = kc.makeApiClient(k8s.Custom_objectsApi);
            const d = new k8s.V1DeleteOptions();
            d.propagationPolicy = 'Foreground';
            d.gracePeriodSeconds = 0;

            let nextPromise = Promise.resolve();
            args.operators.forEach(operatorDefinition => {
                if (singleOperatorName !== true && operatorDefinition.key !== singleOperatorName) {
                    console.log(`\n\nOPERATOR ${operatorDefinition.key}\n  - skipping`);
                    return;
                }
                const crd = YAML.parse(loadCustomResourceDefinition(operatorDefinition));
                crd.metadata.name += ".dev";
                crd.spec.group += ".dev";
github Azure / kubernetes-hackfest / app-experimental / kube-api / routes / nodes.js View on Github external
const express = require('express');
const router = express.Router();
const k8s = require('@kubernetes/client-node');
var k8sApi;

if (process.env.K8S_LOCALE != 'CLUSTER') {
  k8sApi = k8s.Config.defaultClient();
} else {
  let kc = new k8s.KubeConfig();
  kc.loadFromCluster();

  k8sApi = new k8s.Core_v1Api(kc.getCurrentCluster()['server']);
  k8sApi.setDefaultAuthentication(kc);
}

/* GET ALL NODES */
router.get('/', function(req, res, next) {
  var nodes = [];
  k8sApi.listNode().then(out => {
    out.response.body.items.forEach(function(node, index) {
      nodes.push({
        name: node.metadata.name,
        machineAType: node.metadata.labels['beta.kubernetes.io/instance-type'],
        addresses: node.status.addresses
      });
github netgroup-polito / CrownLabs / qlkube / src / watch.js View on Github external
const k8s = require('@kubernetes/client-node');
const fetch = require('node-fetch');
const { publishEvent } = require('./pubsub.js');

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

// resource needs to be PLURAL
async function canWatchResource(
  apiServerUrl,
  token,
  resource,
  group,
  namespace,
  name
) {
  return fetch(
    `${apiServerUrl}/apis/authorization.k8s.io/v1/selfsubjectaccessreviews`,
    {
      method: 'POST',
github stanford-oval / almond-cloud / tests / unit / test_k8s_api.js View on Github external
server: 'foo.bar.com',
        }
    ],
    contexts: [
        {
            cluster: 'cluster',
            user: 'user',
        }
    ],
    users: [
        {
            name: 'user',
        }
    ],
};
const kc = new k8s.KubeConfig();
Object.assign(kc, fakeConfig);
const k8sApi = kc.makeApiClient(k8s.BatchV1Api);
const k8sCore = kc.makeApiClient(k8s.CoreV1Api);

function testDeleteNamespacedJob() {
    const args = getArgs(k8sApi.deleteNamespacedJob);
    assert.strictEqual(args[0], 'name');
    assert.strictEqual(args[1], 'namespace');
    assert.strictEqual(args[6], 'propagationPolicy');
}

function testListEndpointsForAllNamespaces() {
    const args = getArgs(k8sCore.listEndpointsForAllNamespaces)
    assert.strictEqual(args[2], 'fieldSelector');
}
github godaddy / kubernetes-client / test-integration / env.js View on Github external
async function getClient () {
  if (process.env.KUBERNETES_CLIENT_BACKEND === 'client-node') {
    const kubeconfig = new k8s.KubeConfig()
    kubeconfig.loadFromDefault()
    const backend = new ClientNodeBackend({ kubeconfig })
    const client = new Client({ backend, version: '1.13' })
    return client
  } else {
    const client = new Client({})
    await client.loadSpec()
    return client
  }
}
github kubernetes-client / javascript / examples / example.js View on Github external
const k8s = require('@kubernetes/client-node');

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

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

k8sApi.listNamespacedPod('default')
    .then((res) => {
	console.log(res.body);
    });
github ForetagInc / fullstack-ts-boilerplate / apps / api / src / app / k8s-config.service.ts View on Github external
public static create() {
    const kc = new KubeConfig();
    kc.loadFromFile(path.join(process.cwd(), '.deploy', 'kubeconfig.yml'));
    return kc;
  }
}
github smartive / kuby / src / utils / kubernetes-api.ts View on Github external
public static fromDefault(): KubernetesApi {
    const kubeConfig = new KubeConfig();
    kubeConfig.loadFromDefault();
    return new KubernetesApi(kubeConfig);
  }
github replicatedhq / kots / kotsadm / api / src / kots_app / kots_app_store.ts View on Github external
async getGitopsInfo(appId: string, clusterId: string) {
    try {
      const kc = new k8s.KubeConfig();
      kc.loadFromDefault();
      const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

      const namespace = process.env["POD_NAMESPACE"]!;

      const secretName = "kotsadm-gitops";
      const secret = await k8sApi.readNamespacedSecret(secretName, namespace);
      const secretData = secret.body.data!;

      const configMapName = "kotsadm-gitops";
      const configmap = await k8sApi.readNamespacedConfigMap(configMapName, namespace);

      const appClusterKey = `${appId}-${clusterId}`;
      if (!(appClusterKey in configmap.body.data!)) {
        throw new ReplicatedError(`No gitops data found for app with id ${appId} and cluster with id ${clusterId}`);
      }
github pixel-point / kube-forwarder / src / renderer / components / shared / cluster / ClusterForm.vue View on Github external
async handleOpenFile(method) {
      const filePaths = await showOpenDialog({ properties: ['openFile'] })
      if (!filePaths) return

      const fileStats = await fs.stat(filePaths[0])
      if (fileStats.size > size.MBYTE) return showErrorBox('Sorry, the file is too large (> 1MB)')

      const content = await fs.readFile(filePaths[0], { encoding: 'utf8' })

      if (method === configStoringMethods.CONTENT) {
        this.attributes.config.content = content
      }

      if (method === configStoringMethods.PATH) {
        let kubeConfig = new KubeConfig()
        try {
          kubeConfig.loadFromString(content)
        } catch (error) {
          kubeConfig = null
          const result = await showConfirmBox(
            `The files contains invalid config. \nError ${error.message}.\n\n Do you want to continue?`
          )
          if (!result) return
        }

        this.attributes.config.path = filePaths[0]
        if (kubeConfig) {
          this.attributes.config.currentContext = kubeConfig.getCurrentContext()
          this.contexts = kubeConfig.contexts
        } else {
          this.contexts = []