How to create a Kubernetes deployment using the Node.js SDK

2/11/2021

I am working on building a project using Node.js which will require me to have an application that can deploy to Kubernetes. The service I am working on will take some Kubernetes manifests, add some ENV variables into them, and then would deploy those resources.

I have some code that can create and destroy a namespace for me using the SDK and createNamespace and deleteNamespace. This part works how I want it to, ie without needing a Kubernetes YAML file. I would like to use the SDK for creating a deployment as well however I can't seem to get it to work. I found a code example of createNamespacedDeployment however using version 0.13.2 of the SDK I am unable to get that working. I get this error message when I run the example code I found.

k8sApi.createNamespacedDeployment is not a function

I have tried to check over the git repo for the SDK though it is massive and I've yet to find anything in it that would allow me to define a deployment in my Node.js code, closest I have found is a pod deployment however that won't work for me, I need a deployment.

How can I create a deployment via Node.js and have it apply to my Kubernetes cluster?

-- joshk132
kubernetes
kubernetes-deployment
node.js

1 Answer

2/12/2021

You can use the @c6o/kubelcient kubernetes client. It's a little simpler:

import { Cluster } from '@c6o/kubeclient'

const cluster = new Cluster({}) // Assumes process.env.KUBECONFIG is set
const result = await cluster.upsert({kind: 'Deployment', apiVersion.. })
if (result.error) ...

You can also it using the fluent API if you have multiple steps:

           await cluster
            .begin(`Provision Apps`)
                .upsertFile('../../k8s/marina.yaml', options)
                .upsertFile('../../k8s/store.yaml', options)
                .upsertFile('../../k8s/harbourmaster.yaml', options)
                .upsertFile('../../k8s/lifeboat.yaml', options)
                .upsertFile('../../k8s/navstation.yaml', options)
                .upsertFile('../../k8s/apps.yaml', options)
                .upsertFile('../../k8s/istio.yaml', options)
            .end()

We're working on the documentation but have lots of provisioners using this client here: https://github.com/c6o/provisioners

-- Narayan Sainaney
Source: StackOverflow