How to use @kubernetes/client-node - 10 common examples

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 kubernetes-client / javascript / examples / namespace.js View on Github external
const k8s = require('@kubernetes/client-node');

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

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

var namespace = {
  metadata: {
    name: 'test'
  }
};

k8sApi.createNamespace(namespace).then(
  (response) => {
    console.log('Created namespace');
    console.log(response);
    k8sApi.readNamespace(namespace.metadata.name).then(
      (response) => {
        console.log(response);
	k8sApi.deleteNamespace(
          namespace.metadata.name, {} /* delete options */);
github kubernetes-client / javascript / examples / typescript / watch / watch-example.ts View on Github external
import * as k8s from '@kubernetes/client-node';

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

const watch = new k8s.Watch(kc);
const req = watch.watch('/api/v1/namespaces',
    // optional query parameters can go here.
    {},
    // callback is called for each received object.
    (type, obj) => {
        if (type === 'ADDED') {
            // tslint:disable-next-line:no-console
            console.log('new object:');
        } else if (type === 'MODIFIED') {
            // tslint:disable-next-line:no-console
            console.log('changed object:');
        } else if (type === 'DELETED') {
            // tslint:disable-next-line:no-console
            console.log('deleted object:');
        } else {
            // tslint:disable-next-line:no-console
github jenkins-x / vscode-jx-tools / src / KubeWatcher.ts View on Github external
connect() {
        if (!this.connected) {
            this.connected = true;

            let kc = new k8s.KubeConfig();
            let configFile = process.env['HOME'] + '/.kube/config';
            try {
                kc.loadFromFile(configFile);
            } catch (e) {
                console.log('error reading ' + configFile + ': ' + e.message);
                throw e;
            }
            
            //let resourceVersion = 0
            let watch = new k8s.Watch(kc);

            // optional query parameters can go here.
            // TODO filter on labels once we add them to Activities
            const queryParameters = {};

            // callback is called for each received object.
            const callback = (type: any, obj: any) => {
                if (type === 'ADDED') {
                    this.notify(CallbackKind.ADD, obj);
                }
                else if (type === 'MODIFIED') {
                    this.notify(CallbackKind.UPDATE, obj);
                }
                else if (type === 'DELETED') {
                    this.notify(CallbackKind.DELETE, obj);
                }
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";

                nextPromise = nextPromise
                    .then(() => console.log(`\n\nOPERATOR ${operatorDefinition.key}`))
                    // 2) Delete/Create "DEV" CRDs
github kubernetes-client / javascript / examples / yaml-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);

const yamlString = k8s.dumpYaml({
  metadata: {
    name: 'test'
  }
});

const yamlNamespace = k8s.loadYaml(yamlString);

k8sApi.createNamespace(yamlNamespace).then(
  (response) => {
    console.log('Created namespace');
    console.log(response);
    k8sApi.readNamespace(yamlNamespace.metadata.name).then(
      (response) => {
        console.log(response);
        k8sApi.deleteNamespace(
          yamlNamespace.metadata.name, {} /* delete options */);
      });
  },
  (err) => {
    console.log('Error!: ' + err);
  }
);
github hyperflow-wms / hyperflow / functions / k8sCommand.js View on Github external
async function k8sCommand(ins, outs, context, cb) {

  let handlerStart = Date.now();
  console.log("[DEBUG] K8sInvoke called.");
  // let cluster = await getCluster();
  // const token = await getGCPToken();

  const kc = new k8s.KubeConfig();
  kc.loadFromDefault(); // loadFromString(JSON.stringify(kconfig))

  const k8sApi = kc.makeApiClient(k8s.BatchV1Api);
  try {
    var command = 'hflow-job-execute ' + context.taskId + ' ' + context.redis_url;
    var containerName = process.env.HF_VAR_WORKER_CONTAINER;
    var volumePath = '/work_dir';
    var jobName = Math.random().toString(36).substring(7);
    //var jobName = context.name + "_" + context.taskId.replace(/:/g, '_');

    // Load definition of the the worker job pod
    // File 'job-template.yaml' should be provided externally during deployment
    var job_template_path = process.env.HF_VAR_JOB_TEMPLATE_PATH || "./job-template.yaml";
    var jobYaml = fs.readFileSync(job_template_path, 'utf8');
    //var job = yaml.safeLoad(eval('`'+jobYaml+'`')); // this works, but eval unsafe

    // use string replacement instead of eval to evaluate job template
    // 'params' should contain values for variables to be replaced in job template yaml
    var params = {
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";

                nextPromise = nextPromise
                    .then(() => console.log(`\n\nOPERATOR ${operatorDefinition.key}`))
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',