How can I generate a `V1Job` object for the Kubernetes nodejs API client from a yaml file?

7/11/2019

I've done this previously in python using:

    with open(path.join(path.dirname(__file__), "job.yaml")) as f:
        body= yaml.safe_load(f)

        try:
            api_response = api_instance.create_namespaced_job(namespace, body)

Looking at source of the nodejs api client:

    public createNamespacedJob (namespace: string, body: V1Job, includeUninitialized?: boolean, pretty?: string, dryRun?: string, options: any = {}) : Promise<{ response: http.IncomingMessage; body: V1Job;  }> {

How can I generate that the V1Job?


I've tried the below but get back a very verbose error message / response:

const k8s = require('@kubernetes/client-node');
const yaml = require('js-yaml');
const fs   = require('fs');

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

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

var namespace = {
    metadata: {
        name: 'test123',
    },
};

try {
    var job = yaml.safeLoad(fs.readFileSync('job.yaml', 'utf8'));

    k8sApi.createNamespacedJob(namespace, job).then(
        (response) => {
            console.log('Created namespace');
            console.log("Success!")
        },
        (err) => {
            console.log(err);
            console.log(job);
            console.log("Err")
        },
    );

} catch (e) {
    console.log(e);
}
-- Chris Stryczynski
javascript
kubernetes
node.js

1 Answer

7/11/2019
  1. V1Job seems to be an ordinary object so the below worked.
  2. Namespace had to be a string rather than an object...
const k8s = require('@kubernetes/client-node');
const yaml = require('js-yaml');
const fs   = require('fs');

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

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

try {
    var job = yaml.safeLoad(fs.readFileSync('job.yaml', 'utf8'));

    k8sApi.createNamespacedJob("default", job).then(
        (response) => {
            console.log("Success")
        },
        (err) => {
            console.log(e);
            process.exit(1);
        },
    );

} catch (e) {
    console.log(e);
    process.exit(1);
}
-- Chris Stryczynski
Source: StackOverflow